mongoose 只给出子文档的_id 时如何查询子文档?
How to query for a subdocument when only _id of the subdocument is given in mongoose?
我在数据库中有一个文档的快照,如下所示
{
"_id" : ObjectId("624e105df043d4ad4ee893ee"),
"title" : "First post",
"author" : "Rituparna",
"comments" : [
{
"content" : "First comment",
"author" : "Ritu",
"_id" : ObjectId("624e109b966fbe64b2a80ea9"),
"replies" : [ ]
},
{
"content" : "second comment",
"author" : "Ritu",
"_id" : ObjectId("624e10a4e33f7962d0002f39"),
"replies" : [ ]
}
],
"__v" : 0
}
现在假设你只得到一个评论的_id,说第一个评论624e109b966fbe64b2a80ea9
我要找的最终结果是
{
"content" : "First comment",
"author" : "Ritu",
"_id" : ObjectId("624e109b966fbe64b2a80ea9"),
"replies" : [ ]
}
当我只得到评论的 _id 和 Post 模型(子文档模型的父模型)时,我需要编写什么查询?
db.collection.aggregate([
{
$match: { "comments._id": ObjectId("624e109b966fbe64b2a80ea9") }
},
{
$unwind: "$comments"
},
{
$match: { "comments._id": ObjectId("624e109b966fbe64b2a80ea9") }
},
{
$replaceWith: "$comments"
}
])
我在数据库中有一个文档的快照,如下所示
{
"_id" : ObjectId("624e105df043d4ad4ee893ee"),
"title" : "First post",
"author" : "Rituparna",
"comments" : [
{
"content" : "First comment",
"author" : "Ritu",
"_id" : ObjectId("624e109b966fbe64b2a80ea9"),
"replies" : [ ]
},
{
"content" : "second comment",
"author" : "Ritu",
"_id" : ObjectId("624e10a4e33f7962d0002f39"),
"replies" : [ ]
}
],
"__v" : 0
}
现在假设你只得到一个评论的_id,说第一个评论624e109b966fbe64b2a80ea9
我要找的最终结果是
{
"content" : "First comment",
"author" : "Ritu",
"_id" : ObjectId("624e109b966fbe64b2a80ea9"),
"replies" : [ ]
}
当我只得到评论的 _id 和 Post 模型(子文档模型的父模型)时,我需要编写什么查询?
db.collection.aggregate([
{
$match: { "comments._id": ObjectId("624e109b966fbe64b2a80ea9") }
},
{
$unwind: "$comments"
},
{
$match: { "comments._id": ObjectId("624e109b966fbe64b2a80ea9") }
},
{
$replaceWith: "$comments"
}
])