我有一个mongo查询
db.memberships.aggregate([{
'$match': {
unit: new ObjectId('566fbaa1e63225b10bacac44')
}
},
{
'$lookup': {
from: 'seasons',
localField: 'season',
foreignField: '_id',
as: 'season'
}
},
{
'$unwind': '$season'
},
{
'$project': {
season: {
'name': '$season.name',
'id': '$season._id'
}
}
},
{
'$group': {
_id: '$_id',
'season': {
'$addToSet': '$season'
}
}
},
]);
结果是
[
{
"_id": ObjectId("56a0e5a860d8a6e41eda2ea3"),
"season": [{
"name": "Summer",
"id": ObjectId("56a0d6c692c26b8c019a2758")
}]
},
{
"_id": ObjectId("56a0e56d60d8a6e41eda2e9e"),
"season": [{
"name": "Summer",
"id": ObjectId("56a0d6c692c26b8c019a2758")
}]
},
{
"_id": ObjectId("56a0e53860d8a6e41eda2e9a"),
"season": [{
"name": "Summer",
"id": ObjectId("56a0d6c692c26b8c019a2758")
}]
},
{
"_id": ObjectId("56a0e4d660d8a6e41eda2e94"),
"season": [{
"name": "Winter",
"id": ObjectId("5680dc01ba1e41f5066526fa")
}]
}
]
我需要以这种格式获得结果
{
_id: [
// ids here
],
seasons: [{
id: '56a0d6c692c26b8c019a2758',
'name': 'Summer'
},
{
id: '5680dc01ba1e41f5066526fa',
'name': 'Winter'
}
]
}
查询必须返回包含2个属性id
和season
的单个文档。季节必须是一系列独特的季节。每个季节都应该包含一个id和一个名字。谢谢你的帮助!
答案 0 :(得分:1)
使用 $group
步骤重构您的管道,使_id
值为null
,以计算所有输入文档的累计值,从而将id字段创建为所有唯一ID的数组:
var pipeline = [
{
'$match': {
unit: new ObjectId('566fbaa1e63225b10bacac44')
}
},
{
'$lookup': {
from: 'seasons', localField: 'season', foreignField: '_id', as: 'season'
}
},
{
'$unwind' : '$season'
},
{
'$project': {
season: {'name': '$season.name', 'id' : '$season._id'}
}
},
{
'$group': {
"_id": null,
"id": { "$addToSet": "$_id" },
'season': {
'$addToSet': '$season'
}
}
}
];
db.memberships.aggregate(pipeline);