2015-12-09 99 views
0

我的模式是這樣的陣列領域的項目只返回基於子文檔_id子文件,它是MongoDB的文檔

[ 
{ 
    "_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") 
}] 

我所缺少的,請建議.. 謝謝

回答

5

您可以在投影使用$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") 
    } 
    ] 
} 
+0

感謝名單的傢伙,我被困在這個問題上和其他解決方案並沒有爲我工作。你是男人:D –