0

I have this collection...

> db.banks.find().pretty() { "_id" : ObjectId("54f37cbb44aec3b01b7db8f4"), "name" : "A", "branches" : [ { "branch_id" : 8561, "name" : "X", }, { "branch_id" : 8576, "name" : "Y", } ] } { "_id" : ObjectId("54f37cbb44aec3b01b7db8f5"), "name" : "B", "branches" : [ { "branch_id" : 3238, "name" : "Z", } ] } 

with this command :

db.banks.aggregate({$project{"branches.name":1,"_id":0}}); 

get this result :

{ "branches" : { { "name" : "X" }, { "name" : "Y" } } } { "branches" : { { "name" : "Z" } } } 

but; how I get this result? (In fact, one object and without "branches".)

{{"name" : "X"}, {"name" : "Y"}, {"name" : "Z"}} 

very thanks...

1 Answer 1

1

One way you could go about this is to do an $unwind first in the aggregation pipeline to get a deconstructed array with a document for each element and then group by the array element $branches.name:

db.banks.aggregate([ { $unwind: '$branches'}, { $group: { _id: { name: '$branches.name' } } }, { $project: { _id: 0, name: '$_id.name' } }, { $sort : { "name" : 1 } } ]) 

Outputs:

{ "result" : [ { "name" : "X" }, { "name" : "Y" }, { "name" : "Z" } ], "ok" : 1 } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.