我有一个名为group
的数组,其中包含一个ID列表,我在下面的find和populate语句与此完美配合,我使用populate来获取其他数据 - 查询如下:
var stories = await Story
.find( { 'group' : { $in : group } } )
.populate('group')
.populate('createdBy')
.sort('-created')
我有一个聚合查询(下面),它做我想要的但是1)它不使用group
数组中的值,它只返回所有内容,2)我没有得到group
和createdBy
字段的其他数据与上面的find
一样。
var spellings = await Spelling.aggregate([
{ "$sort": { "keyStageLevel": 1, "spellingLevel": 1 } },
{ "$group" : {
"_id": { "keyStageLevel": "$keyStageLevel", "class": "$class" },
"data": {
"$push": {
"spellingLevel": "$spellingLevel",
"class": "$class",
"name": "$name",
"spellings": "$spellings",
"created": "$created",
"_id": "$_id",
"group": "$group",
"createdBy": "$createdBy"
}
}
}},
{ "$sort": { "_id": 1 } }
])
编辑 - 这是拼写文档的示例:
{
"_id":"5b1ff6f62bb1894efcf76ea0",
"spellings":["here","are","spellings"],
"name":"withclass",
"group":"5ab79a639083cf35339b880a",
"createdBy":"5ab79185d47b833506ff94b1",
"created":"2018-06-12T16:38:14.571Z",
}
任何人都可以帮助我如何使用group
语句中aggregate
数组中的值以及我如何添加group
和createdBy
的其他数据像find
那样的字段?
答案 0 :(得分:1)
您可以尝试在$lookup
聚合下方填充group
和createdBy
字段
var spellings = await Spelling.aggregate([
{ "$match": { "group": { "$in": group }}},
{ "$sort": { "keyStageLevel": 1, "spellingLevel": 1 } },
{ "$lookup": {
"from": CreatedBy.collection.name,
"let": { "createdBy": "$createdBy" },
"pipeline": [
{ "$match": { "$expr": { "$eq": [ "$_id", "$$createdBy" ] } } }
],
"as": "createdBy"
}},
{ "$lookup": {
"from": Group.collection.name,
"let": { "group": "$group" },
"pipeline": [
{ "$match": { "$expr": { "$eq": [ "$_id", "$$group" ] } } }
],
"as": "group"
}},
{ "$unwind": "$group" },
{ "$unwind": "$createdBy" },
{ "$group" : {
"_id": { "keyStageLevel": "$keyStageLevel", "class": "$class" },
"data": {
"$push": {
"spellingLevel": "$spellingLevel",
"class": "$class",
"name": "$name",
"spellings": "$spellings",
"created": "$created",
"_id": "$_id",
"group": "$group",
"createdBy": "$createdBy"
}
}
}},
{ "$sort": { "_id": 1 } }
])