Saturday, 15 August 2015

Get specific object in array of array in MongoDB -



Get specific object in array of array in MongoDB -

i need specific object in array of array in mongodb.

i need task object = [_id = objectid("543429a2cb38b1d83c3ff2c2")].

my document (projects):

{ "_id" : objectid("543428c2cb38b1d83c3ff2bd"), "name" : "new project", "author" : objectid("5424ac37eb0ea85d4c921f8b"), "members" : [ objectid("5424ac37eb0ea85d4c921f8b") ], "us" : [ { "_id" : objectid("5434297fcb38b1d83c3ff2c0"), "name" : "test story", "author" : objectid("5424ac37eb0ea85d4c921f8b"), "tasks" : [ { "_id" : objectid("54342987cb38b1d83c3ff2c1"), "name" : "teste3", "author" : objectid("5424ac37eb0ea85d4c921f8b") }, { "_id" : objectid("543429a2cb38b1d83c3ff2c2"), "name" : "jklasdfa_xxx", "author" : objectid("5424ac37eb0ea85d4c921f8b") } ] } ] }

result expected:

{ "_id" : objectid("543429a2cb38b1d83c3ff2c2"), "name" : "jklasdfa_xxx", "author" : objectid("5424ac37eb0ea85d4c921f8b") }

but not getting it. still testing no success:

db.projects.find({ "us.tasks._id" : objectid("543429a2cb38b1d83c3ff2c2") }, { "us.tasks.$" : 1 })

i tryed $elemmatch too, homecoming nothing.

db.projects.find({ "us" : { "tasks" : { $elemmatch : { "_id" : objectid("543429a2cb38b1d83c3ff2c2") } } } })

can result expected using find()? if not, , how use?

thanks!

you need aggregation that:

db.projects.aggregate([{$unwind:"$us"}, {$unwind:"$us.tasks"}, {$match:{"us.tasks._id":objectid("543429a2cb38b1d83c3ff2c2")}}, {$project:{_id:0,"task":"$us.tasks"}}])

should return

{ task : { "_id" : objectid("543429a2cb38b1d83c3ff2c2"), "name" : "jklasdfa_xxx", "author" : objectid("5424ac37eb0ea85d4c921f8b") }

explanation:

$unwind creates new (virtual) document each array element $match query part of find $project similar project part in find i.e. specifies fields want in results

you might want add together sec $match before $unwind if know document searching (look @ performance metrics).

edit: added sec $unwind since us array.

don't know doing (so realy can't tell , sugesting) might want examine if schema (and mongodb) ideal task because document looks denormalized relational info relational database improve you.

arrays mongodb collections nosql find

No comments:

Post a Comment