spring - 提取数组的值并添加到同一个选择的mongoDB中

标签 spring mongodb spring-boot mongodb-query aggregation-framework

我是mongoDB聚合的新手,遇到这种情况。我有这个 Json,我需要通过“选择”这个对象来转换:

{
    "type": "PF",
    "code": 12345
    "Name": Darth Vader,
    "currency": "BRL",
    "status": "SINGLE",
    "adress": [
        {
            "localization": "DEATH STAR",
            "createDate": 1627990848665
        },
        {
            "localization": "TATOOINE",
            "createDate": 1627990555665
        },
    ]
}

这样:

{
    "type": "PF",
    "code": 12345
    "Name": Darth Vader,
    "currency": "BRL",
    "status": "SINGLE",
    "localization": "DEATH STAR",
    "createDate": 1627990848665
},
{
    "type": "PF",
    "code": 12345
    "Name": Darth Vader,
    "currency": "BRL",
    "status": "SINGLE",
    "localization": "TATOOINE",
    "createDate": 1627990555665
}

因此,在我的查询完成后,我将拥有 02 个对象而不是 01 个。我该怎么做? 我想通过 select 执行此操作,因为转换后我将按 createDate 排序并限制返回 API 的记录数。我在我的项目中使用 Criteria。

最佳答案

执行此操作的方法是 $unwind,这将为数组的每个成员制作 1 个文档副本。

Test code here

db.collection.aggregate([
  {
    "$unwind": {
      "path": "$user.adress"
    }
  },
  {
    "$set": {
      "user": {
        "$mergeObjects": [
          "$user",
          "$user.adress"
        ]
      }
    }
  },
  {
    "$unset": [
      "user.adress"
    ]
  },
  {
    "$sort": {
      "createDate": 1
    }
  },
  {
    "$limit": 10
  }
])

Edit1(上面是如果user是一个字段,如果是集合的名字)

  • $$ROOT 是一个系统变量,它的值是整个文档

Test code here

查询

db.collection.aggregate([
  {
    "$unwind": {
      "path": "$adress"
    }
  },
  {
    "$replaceRoot": {
      "newRoot": {
        "$mergeObjects": [
          "$$ROOT",
          "$adress"
        ]
      }
    }
  },
  {
    "$unset": [
      "adress"
    ]
  },
  {
    "$sort": {
      "createDate": 1
    }
  },
  {
    "$limit": 10
  }
])

关于spring - 提取数组的值并添加到同一个选择的mongoDB中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69004637/

相关文章:

java - 将 jhipster 应用程序部署到不同的上下文路径

java - 是否有任何选项可以使用 Spring-AMQP 在 RabbitMQ 中设置 AutomaticRecoveryEnabled?

spring - Kotlin 和 Spring Boot @ConfigurationProperties

java - spring-boot application.properties 中的环境变量错误

java - 在异步 Thrift 客户端中传递 URI/上下文路径

java - 将 Spring XML 配置转换为 Java 配置

Spring 4(无启动)与自定义 Jackson ObjectMapper

Mongodb 分片和索引

node.js - express.js/mongo 的 Eslint 配置

node.js - 当 mongodb 服务器关闭时如何在运行 mongoose 查询时捕获错误