如何通过排除一个命名字段来获取不同的子文档列表?

时间:2017-12-04 11:40:00

标签: mongodb

我正在寻找一个前3.4解决方案(即没有replaceRoot和项目排除选项),通过排除一个命名字段来获取不同的子文档值列表。

我有类似的东西: -

{
"field1":"sadasdasdasdas",
"field2":"whatever bla dasdasda",
"source_display_tags" : {
        "name" : "Hot Toast Cafe",
        "updateId" : NumberLong(12345),
        "address" : "2 Burnt Street",
        "postal_code" : "HT1 8RT",
        "town" : "Breadville"
    }
}

我希望通过排除updateId字段来获取一个独特的source_display_tags列表,即

{
    "source_display_tags" : {
        "name" : "Hot Toast Cafe",
        "address" : "2 Burnt Street",
        "postal_code" : "HT1 8RT",
        "town" : "Breadville"}
},
{
    "source_display_tags" : {
        "name" : "Banana Grove Restaurant",
         etc...

以某种方式不涉及命名任何其他字段。即我不想这样做: -

db.getCollection('updates').aggregate([
{$unwind:"$source_display_tags"},
{"$project": {_id:0, name: "$source_display_tags.name", address: "$source_display_tags.address", town: "$source_display_tags.town", postal_code: "$source_display_tags.postal_code"}},
{ $group: { _id: { name: "$name", address: "$address", town: "$town", postal_code:"$postal_code"}}}
])

有没有办法只通过命名“updateId”字段来生成此输出

1 个答案:

答案 0 :(得分:0)

在现有查询中添加另一个$project,这将为我们带来魔力,在$ project管道中有一个名为source_display_tags的标记,并传递_id的内容(来自以前的管道结果)到此标记并禁止_id

这是查询

db.getCollection('updates').aggregate([ 
     {$unwind:"$source_display_tags"}, 
     {"$project": { _id:0,
               name: "$source_display_tags.name", 
               address: "$source_display_tags.address", 
               town: "$source_display_tags.town", 
               postal_code: "$source_display_tags.postal_code"
     }}, 
     { "$group": {
                _id: {
                        name: "$name",
                        address: "$address",
                        town: "$town", 
                        postal_code:"$postal_code"
                }}
      }, 
      {"$project":{source_display_tags: "$_id", "_id":0}} 
])

如果不需要分组,我们可以简单地使用以下查找

db.so.find( {},
            {
             "source_display_tags.name":1,
              "source_display_tags.address":1, 
              "source_display.tags.postal_code":1, 
              "source_display_tags.town":1, 
              _id:0
            }
);