我的架构就像这样
[
{
"_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 .....选择特定的comments数组项目,但不是只返回特定注释而是返回整个文档。
目前我有以下查询
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")
}]
我缺少的请建议.. 谢谢
答案 0 :(得分:10)
您可以在投影中使用$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")
}
]
}