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

时间:2016-01-07 12:06:43

标签: mongodb aggregation-framework pymongo

数据结构如下:

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

我想在answercomment中像这样查询数组

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

但它不起作用......

出了什么问题?

1 个答案:

答案 0 :(得分: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"}}
])