DB如下。
收藏:评论
{
"_id" : ObjectId("5bc4348f8e798ccb030991e8")
"comment_no" : 143,
“comment_content” : “test test”
}
收藏集:发表
{
"_id" : ObjectId("5bc16b068e798ccb03096efa"),
"post_no" : 48,
"comment" : [
{
"comment_no" : 143,
"comment_group" : 1 // This value will disappear.
}
]
}
查询如下:
db.getCollection('post').aggregate([
{
$match : {post_no: 48}
},
{
$lookup: {
from: 'comment'
localField: 'comment.comment_no',
foreignField: 'comment_no',
as: 'comment'
}
}
])
结果如下。
{
"_id" : ObjectId("5bc16b068e798ccb03096efa"),
"post_no" : 48,
"comment" : [
{
"comment_no" : 143,
“comment_content” : “test test”
}
]
}
现有数据消失了,但是我想合并comment_group的值。
例如,我想要的结果是..
{
"_id" : ObjectId("5bc16b068e798ccb03096efa"),
"post_no" : 48,
"comment" : [
{
"comment_no" : 143,
“comment_content” : “test test”,
"comment_group" : 1 // Here!! I want to use this value.
}
]
}
我可以查询以便将值合并到comment_no吗?
答案 0 :(得分:2)
您可以尝试以下汇总
您需要首先$unwind
comment
数组以与确切的comment_no
匹配,然后$group
才能再次回滚到其原始格式
db.getCollection("post").aggregate([
{ "$match": { "post_no": 48 }},
{ "$unwind": "$comment" },
{ "$lookup": {
"from": "comment"
"localField": "comment.comment_no",
"foreignField": "comment_no",
"as": "comment.comment_content"
}},
{ "$unwind": "$comment.comment_content" },
{ "$addFields": {
"comment": {
"$mergeObjects": ["$comment", "$comment.comment_content"]
}
}},
{ "$group": {
"_id": "$_id",
"comment": { "$push": "$comment" }
}}
])
答案 1 :(得分:0)
您可以这样获得所需的东西:
db.post.aggregate([
{
$match : { post_no: 48 }
}, {
$unwind: '$comment' // flatten 'comment' array into sub-documents
}, {
$lookup: {
from: 'comment',
let: {
'comment': '$comment', // keep a reference to the 'comment' sub-document
},
pipeline: [{
$match: { $expr: { $eq: [ '$comment_no', '$$comment.comment_no' ] } } // perform the join
}, {
$replaceRoot: { "newRoot": { $mergeObjects: [ '$$comment', '$$ROOT' ] } } // merge the found object with the original content of 'comment'
}],
as: 'comment'
}
}, {
$group: { // restore the original structure
_id: '$_id',
'comment': { $push: { $arrayElemAt: [ '$comment', 0 ] } }
}
}])