在mongoDB聚合中选择组后的所有字段

时间:2019-02-17 00:15:22

标签: mongodb mongodb-query aggregation-framework

我在mongoDB中有文档,例如:

{
    "_id": "myId",
    "firstName": "myFirstName",
    "lastName": "myLastName",
    "email": "my@email.com",
    "age": 88,
    "city": "myCity",
    "country": "myCountry"
}

然后,我在管道中有_id提供的lookupunwindgroup。当我需要所有字段时,有什么方法可以不列出所有字段?

{
    $group: {
        "_id": "$_id",
        "someItemsFromLookup": { "$push": "$someItemsFromLookup" }
        "firstName": { "$first": "$firstName" },
        "lastName": { "$first": "$lastName" },
        "email": { "$first": "$email" },
        "age": { "$first": "$age" },
        "city": { "$first": "$city" },
        "country": { "$first": "$country" }
    }
}

我需要这样的内容,其中*是“所有字段”:

{
    $group: {
        "_id": "$_id",
        "someItemsFromLookup": { "$push": "$someItemsFromLookup" }
        "*": { "$first": "*" },
    }
}

2 个答案:

答案 0 :(得分:2)

您可以将$$ROOT$first累加器一起使用,然后将$replaceRoot与第一个字段一起使用以将其放在根位置。

{ "$group": {
  "_id": "$_id",
  "someItemsFromLookup": { "$push": "$someItemsFromLookup" },
  "first": { "$first": "$$ROOT" }
}},
{ "$replaceRoot": {
  "newRoot": {
    "$mergeObjects": [
      "$first",
      { "someItemsFromLookup": "$someItemsFromLookup" }
    ]
  }
}}

答案 1 :(得分:1)

您可以将$first$$ROOT一起使用

{
    $group: {
        "_id": "$_id",
        "someItemsFromLookup": { "$push": "$someItemsFromLookup" },
        "firstDocument": { "$first": "$$ROOT" }
    }
}