db={
comments: [
{
"_id": ObjectId("5f364189f412c01fd01abab3"),
"content": "Comment 1",
"parent_comment_id": "",
"date": 1592461538923
},
{
"_id": ObjectId("5f364642f412c01fd01abeu4"),
"content": "Replied",
"parent_comment_id": "5f364189f412c01fd01abab3",
"date": 1592461538926
},
{
"_id": ObjectId("5f364642f412c01fd01abtx5"),
"content": "fresh comment",
"parent_comment_id": "",
"date": 1592461538929
}
]
}
如何在基于parent_comment_id的mongodb中实现自我连接。
在mongodb中是否有可能像mysql一样?
使用聚合gregation(),
parent_comment_id
为对象(如果不为空),如果它已经是对象ID,则跳过此管道db.comments.aggregate([
{
$addFields: {
parent_comment_id: {
$cond: {
if: { $eq: ["$parent_comment_id", ""] },
then: "$parent_comment_id",
else: { $toObjectId: "$parent_comment_id" }
}
}
}
},
{
"$lookup": {
from: "comments",
le": { pid: "$parent_comment_id" },
as: "parentComment",
pipeline: [
{
$match: {
$expr: { $eq: ["$$pid", "$_id" ] }
}
}
]
}
},
parentComment
因为它是一个数组,我们需要一个对象preserveNullAndEmptyArrays
忽略空parentComment
数组 {
$unwind: {
path: "$parentComment",
preserveNullAndEmptyArrays: true
}
}
])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句