如何使用 $project 根据选定的 id 检索目标数组?

how to use $project to retrieve targeted array according to selected id?

数据结构如下:

{
        "_id" : "10001",
        "comments" : [
                {
                        "comid" : "3",
                        "comtime" : "2014",
                        "author" : "jenny",
                        "replycomment" : [
                                {
                                        "comid" : "34",
                                        "comtime" : "2015",
                                        "author" : "jack"
                                }
                        ]
                }
        ]
}

我想在这样的回复评论中查询数组

db.collection.aggregate([{"$project":{"comments":{"replycomment":{"comtime":1}}}},{"$match":{"comments.comid":"3"}}])

但是没用...

有什么问题吗?

投影后没有更多的字段"comments.comid"所以你不能匹配它。

尝试在投影前匹配或将字段 "comments.comid" 添加到您的投影:

db.collection.aggregate([
    {"$match":{"comments.comid":"3"}},
    {"$project":{_id:0, "comments":{"replycomment": {"comtime":1}}}},
    {"$project":{"replycomment":"$comments.replycomment"}}
])

db.collection.aggregate([
    {"$project":{_id:0, "comments":{comid:1, "replycomment": {"comtime":1}}}},
    {"$match":{"comments.comid":"3"}},
    {"$project":{_id:0, "replycomment":"$comments.replycomment"}}
])