MongoDB positional operator with nested arrays -


sample collection structure:

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

i select comments author objectid("57cfd09401ca2dd672cfebab").

this query working,

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

but return first matching comment positional operator. not working. mongodb support positional operator nested arrays?

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

you having more 2 level of nesting ...find() may not work ,instead try aggregation:-

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

output:

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

Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

serialization - Convert Any type in scala to Array[Byte] and back -

SonarQube Plugin for Jenkins does not find SonarQube Scanner executable -