【问题标题】:How to get List of IDs available in Objects of sub-array如何获取子数组对象中可用的 ID 列表
【发布时间】:2018-12-05 15:13:21
【问题描述】:

StackOverflow 社区,我有一个类似这个家伙的问题 How to get only List of IDs of JSON Objects?

但我需要使用 MongoDB 查询来完成,因为我需要查询大量数据。

我有 1 个这样的对象:

{ 
"_id": ObjectId(".."),
"data": 
 [

    {
      customId : 22,
      customArr:[
           321,
           123
      ]
    },
    {
      customId : 33,
      customArr:[
           123
      ]
    },
    {
      customId : 22,
      customArr:[
      ]
    }
 ]
}

(ofc 有更多数据,但只有这一点对此很重要) 问题: 我不知道如何获取这样的列表:

[22, 33]

[123, 321]

我需要这些列表来计算我的数据,但我目前完全无法计算任何东西。 我不能改变我的结构,因为我已经积累了大量这种格式的数据,它会破坏我的整个应用程序。

我使用的是 MongoDB 3.4,所以所有 3.2 聚合更新都可用, 但我无法让它工作。

谁能给我链接我需要阅读才能完成此任务的文档?或者给出我需要的 MongoDB 函数的任何提示?

提前感谢您的帮助,如果我找到解决方案,我会发布我的解决方案

【问题讨论】:

  • 你可以试试thisdb.collection.aggregate([ { $project: { customId: { $setUnion: "$data.customId" }, customArr: { $reduce: { input: "$data", initialValue: [], in: { $setUnion: [ "$$this.customArr", "$$value" ] } } } } } ])
  • 天哪,感谢这个完美的作品,我觉得很愚蠢,我曾经有过类似的查询......

标签: mongodb performance nosql mongodb-query aggregation-framework


【解决方案1】:

你可以使用下面的聚合

db.collection.aggregate([
  { "$project": {
    "customId": { "$setUnion": "$data.customId" },
    "customArr": {
      "$reduce": {
        "input": "$data",
        "initialValue": [],
        "in": { "$setUnion": ["$$this.customArr", "$$value"] }
      }
    }
  }}
])

【讨论】:

    猜你喜欢
    • 2021-02-03
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 2020-03-29
    • 1970-01-01
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    相关资源
    最近更新 更多