我想使用MongoDB聚合来填充评论中的用户.我可以轻松地使用它来使用$lookup运算符填充createdBy. 我的问题是有一种方法可以使用$each运算符聚合或类似的东西来填充评论中的用户? 我尝试
我的问题是有一种方法可以使用$each运算符聚合或类似的东西来填充评论中的用户?
我尝试使用Mongo 3.2,但在某处我读到它会成为3.4中类似的新功能吗?
我想逃避使用$unwind和$groups(我成功地做了)和类似的事情,以便查询不会成为意大利面条代码.
用户:
{
"_id" : ObjectId("582c31d4afd9252c8515a88b"),
"fullName": "test1"
},
{
"_id" : ObjectId("582c3db0afd9252c8515a88d"),
"fullName": "test2"
}
和帖子:
{
"_id" : ObjectId("5829cac7e9c0994d3db718f8"),
"imgUrl": "images/test.jpg",
"createdBy": ObjectId("582c31d4afd9252c8515a88b"),
"comments": [
{
"_id" : ObjectId("5829cab8e9c0994d3db718f7"),
"content": "blabla",
"user": ObjectId("582c31d4afd9252c8515a88b")
}
]
}
预期产量:
{
"_id" : ObjectId("5829cac7e9c0994d3db718f8"),
"imgUrl": "images/test.jpg",
"createdBy": ObjectId("582c31d4afd9252c8515a88b"),
"comments": [
{
"_id" : ObjectId("5829cab8e9c0994d3db718f7"),
"content": "blabla",
"user": {
"_id" : ObjectId("582c31d4afd9252c8515a88b"),
"fullName": "test1"
}
}
]
}
如果你想使用mongodb的聚合功能,那么你可以使用下面的解决方案.
db.getCollection('posts').aggregate([
{"$unwind":{"path":"$comments","preserveNullAndEmptyArrays":true}},
{ $lookup:
{
from: 'users',
localField: 'comments.user',
foreignField:'_id',
as: 'comments.user'
}
},
{"$unwind":{"path":"$comments.user","preserveNullAndEmptyArrays":true}},
{
$group : {
_id : "$_id",
comments : {$push : "$comments"},
imgUrl : {$first : "$imgUrl"},
createdBy : {$first : "$createdBy"}
}
}
])
确保使用$lookup选项具有3.2.8或更高版本的mongodb
