2016-09-07 4 views
0

structure de collecte de l'échantillon:opérateur de position MongoDB avec des tableaux imbriqués

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

Je voudrais tout sélectionner comments dont author est ObjectId("57cfd09401ca2dd672cfebab").

Cette requête fonctionne,

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

mais je voudrais revenir seulement le premier commentaire correspondant à l'opérateur de position. Quelque chose comme ça ne fonctionne pas. MongoDB prend-il en charge l'opérateur positionnel avec des tableaux imbriqués?

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

Répondre

0

Vous rencontrez plus de deux niveaux d'imbrication ... find() peut ne pas fonctionner, essayez plutôt l'agrégation: -

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

Sortie:

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