我的架构是这样的
[ { "_id" : ObjectId("565f0f5d77f0c7bd11bbadd8"), "blog_id" : ObjectId("56587befdb7224110f007233"), "comments" : [ { "user_id" : ObjectId("562fa014888806820e21e0df"), "user_full_name" : "Niroj Paudel", "comment" : "pradip is bhole baba", "_id" : ObjectId("565f0f5d77f0c7bd11bbadd9"), "dt" : ISODate("2015-12-02T15:33:49.578Z") }, { "user_id" : ObjectId("562fa014888806820e21e0df"), "user_full_name" : "Niroj Paudel", "comment" : "honkog pokhara... he he ha ha", "_id" : ObjectId("565f1034fd07cbfc1129db0b"), "dt" : ISODate("2015-12-02T15:37:24.581Z") } ], "record_count" : 2, "__v" : 0 }]
我正在尝试的是基于blog_id和comments._id .....选择特定的注释项数组,但不是只返回特定注释而是返回整个文档.
目前我有以下查询
db.blog_comments..findOne({ "blog_id" : ObjectId("56587befdb7224110f007233"), "comments._id":ObjectId("565f1034fd07cbfc1129db0b") })
此查询返回整个文档,即 -
[ { "_id" : ObjectId("565f0f5d77f0c7bd11bbadd8"), "blog_id" : ObjectId("56587befdb7224110f007233"), "comments" : [ { "user_id" : ObjectId("562fa014888806820e21e0df"), "user_full_name" : "Niroj Paudel", "comment" : "pradip is bhole baba", "_id" : ObjectId("565f0f5d77f0c7bd11bbadd9"), "dt" : ISODate("2015-12-02T15:33:49.578Z") }, { "user_id" : ObjectId("562fa014888806820e21e0df"), "user_full_name" : "Niroj Paudel", "comment" : "honkog pokhara... he he ha ha", "_id" : ObjectId("565f1034fd07cbfc1129db0b"), "dt" : ISODate("2015-12-02T15:37:24.581Z") } ], "record_count" : 2, "__v" : 0 }]
但我想要这个
[{ "user_id" : ObjectId("562fa014888806820e21e0df"), "user_full_name" : "Niroj Paudel", "comment" : "honkog pokhara... he he ha ha", "_id" : ObjectId("565f1034fd07cbfc1129db0b"), "dt" : ISODate("2015-12-02T15:37:24.581Z") }]
我缺少的请建议..谢谢
你可以$elemMatch
在你的投影中使用:
test> db.project_sub.findOne({ ... "blog_id" : ObjectId("56587befdb7224110f007233") ... },{ ... "comments": { $elemMatch: { _id: ObjectId("565f1034fd07cbfc1129db0b") } } ... }) { "_id": ObjectId("565f0f5d77f0c7bd11bbadd8"), "comments": [ { "user_id": ObjectId("562fa014888806820e21e0df"), "user_full_name": "Niroj Paudel", "comment": "honkog pokhara... he he ha ha", "_id": ObjectId("565f1034fd07cbfc1129db0b"), "dt": ISODate("2015-12-02T15:37:24.581Z") } ] }