【问题标题】:How to group all documents matching for multiple fields mongodb如何对多个字段匹配的所有文档进行分组mongodb
【发布时间】:2021-07-26 17:40:22
【问题描述】:

我是 MongoDB 新手!

我只需要提取所有具有相同地址、类型和 ID 的文档。地址中只有一个地址。其他属性可以有不同的值。例如,请参见下面的测试文档:

{
   "Id" : "123",
   "type" : "T1",
   "addresses" : [ 
       {
        "address" : {
            "line1" : "line 1 ...",
            "line2" : "line 2...",
            "state" : "state1...",
            "city" : "city1...",
            "zip" : "123456"
        }
       }
  ],
   "email" : "test1@gmail.com",
   "salary" : ""
}

例如我下面的文档,第一个值是类型,第二个是 id,第三个是地址,第四个是电子邮件等等:

  doc1 - t1  1  address1  email1 ... 
  doc2 - t1  2  address2  email2 ...
  doc3 - t1  1  address1  email3 ...
  doc4 - t1  1  address1  email4 ...
  doc5 - t1  2  address2  email5 ...
  doc6 - t1  1  address1  email6 ...


outcome: [ [doc1, doc3, doc4, doc6], [doc2, doc5] ]

这里的 doc1、doc3、doc4、doc6 具有相同的 id、类型和地址。和 doc2、doc5 具有相同的 id、类型和地址。

谁能建议如何在 MongoDB 中实现这一点?

【问题讨论】:

  • 如果您发布有效的json文档和预期结果会很好。

标签: mongodb group-by aggregate-functions


【解决方案1】:

在阅读了 Mongo 聚合框架和一些研发之后,我能够使用以下方法实现这一点:

db.getCollection('test_collection').aggregate([  
{
    $group: {
        _id: { type: "$type", id:"$Id", line1: "$addresses.0.address.line1" ... },
        docGroups: { $addToSet: "$$ROOT" }
    }
}
]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 2021-09-11
    • 2022-08-22
    • 2023-03-23
    • 1970-01-01
    • 2014-09-25
    相关资源
    最近更新 更多