b1595021
b1595021

Reputation: 3

How to get value of field in array mongodb

let's assume i have database structure as;

{
    name: "alex",
    age: 21,
    school: [
       {grade: 45, class: "elementary school", name: "blabla"},
       {grade: 89, class: "high school", name: "blabla2"},
       {grade: 12, class: "college", name: "blabla3"}
    ]
},
{
    name: "felix",
    age: 45,
    school: [
       {grade: 12, class: "elementary school", name: "bla"},
       {grade: 45, class: "high school", name: "bla2"},
       {grade: 16, class: "college", name: "bla3"}
    ]
}

what i want to do is get the school name for each name

{
    name: alex,
    school: ["blabla", "blabla2", "blabla3"]
},
{
    name: felix,
    school: ["bla", "bla2", "bla3"]
}

To be able achieve this,

db.collection.aggregate([
    {group: {_id: "$name", school: {$addToSet: {"$school.name"}}}}
])

But couldn't achieve. What should I modify?

Upvotes: 0

Views: 86

Answers (1)

felix
felix

Reputation: 9285

just unwinf the school array before grouping with a $unwind stage like this :

db.collection.aggregate([
  {$unwind: "$school"},
  {$group: {_id: "$name", school: {$addToSet: "$school.name"}}}
])

output:

{ "_id" : "felix", "school" : [ "bla3", "bla2", "bla" ] }
{ "_id" : "alex", "school" : [ "blabla3", "blabla2", "blabla" ] }

Upvotes: 1

Related Questions