Parshuram Kalvikatte
Parshuram Kalvikatte

Reputation: 1646

Return array of fields from subdocument

can anyone please help I want to query mongo to unwind the array,and i am using mongdb native driver My collection document is as follow,Also please ignore my objectId its just for sample

{  
      "_id":ObjectId(123),
      "name":"Sam",
      "age":20,
      "hobbiesDetail":[  
         {  
            "description":"FootBall",
            "level":"20%"
         },
         {  
            "description":"Cricket",
            "level":"80%"
         }
      ]
   },
   {  
      "_id":ObjectId(124),
      "name":"Ted",
      "age":26,
      "hobbiesDetail":[  
         {  
            "description":"FootBall",
            "level":"20%"
         }
      ]
   }

And my expected output is

[  
   {  
      "name":"Sam",
      "age":20,
      "hobbies":"Football,Cricket"
   },
   {  
      "name":"Ted",
      "age":26,
      "hobbies":"Football"
   }
]

I just want to unwind my array and add a comma between hobbies description in one query, Thanx for any help

Upvotes: 0

Views: 189

Answers (1)

Sede
Sede

Reputation: 61273

All you need is a $projection with the $map array operator.

db.collection.aggregate([
    { "$project": { 
        "name": 1, 
        "age": 1, 
        "hobbies": { 
            "$map": { 
                "input": "$hobbiesDetail", 
                "as": "hobby", 
                "in": "$$hobby.description" 
            } 
        } 
    }}
])

Upvotes: 1

Related Questions