2016-09-07 199 views
0

樣品採集結構MongoDB的位置操作:嵌套數組

{ 
"_id" : ObjectId("57cfd62001ca2dd672cfebb1"), 
"name" : "Category", 
"parent" : ObjectId("57cfd5d101ca2dd672cfebb0"), 
"posts" : [ 
    { 
     "name" : "Post", 
     "author" : ObjectId("57cfd09401ca2dd672cfebac"), 
     "content" : "Some content.", 
     "comments" : [ 
      { 
       "author" : ObjectId("57cfd09401ca2dd672cfebab"), 
       "content" : "First comment", 
       "rating" : 2 
      }, 
      { 
       "author" : ObjectId("57cfd09401ca2dd672cfebac"), 
       "content" : "Second comment", 
       "rating" : 5 
      } 
     ] 
    } 
] 
} 

我想選擇所有commentsauthorObjectId("57cfd09401ca2dd672cfebab")

此查詢工作,

db.categories.find({ 'posts.comments.author':ObjectId("57cfd09401ca2dd672cfebab") }) 

,但我想只有首先匹配與位置運算符註釋返回。像這樣的東西不起作用。 MongoDB是否支持嵌套數組的位置操作符?

db.categories.find({ 'posts.comments.author': ObjectId("57cfd09401ca2dd672cfebab") }, 
{ 'posts.comments.$': 1 }) 

回答

0

你有兩個以上級別的嵌套...... find()可能無法正常工作,而是試圖聚集: -

> db.categories.aggregate([{$unwind:"$posts"},{$unwind:"$posts.comments"}, 
{$match:{"posts.comments.author":ObjectId("57cfd09401ca2dd672cfebab")}}, 
{$project:{_id:0,"posts.comments":1}}]).pretty() 

輸出:

{ 
     "posts" : { 
       "comments" : { 
         "author" : ObjectId("57cfd09401ca2dd672cfebab"), 
         "content" : "First comment", 
         "rating" : 2 
       } 
     } 
}