我在mongoDB中有文档,例如:
{
"_id": "myId",
"firstName": "myFirstName",
"lastName": "myLastName",
"email": "my@email.com",
"age": 88,
"city": "myCity",
"country": "myCountry"
}
然后,我在管道中有_id提供的lookup
,unwind
和group
。当我需要所有字段时,有什么方法可以不列出所有字段?
{
$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": "*" },
}
}
答案 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" }
}
}