0

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

4
  • I don't like your expected output how about [ { 'name': 'Sam', 'age': 20, 'hobbies': ['Football', 'Cricket' ] }]? Commented Nov 15, 2016 at 4:54
  • No i cant because i want this to convert to excel,In excel it is not giving proper result for arrays Commented Nov 15, 2016 at 4:57
  • I suggest you return "hobbies" as array and do the remaining work client side. Commented Nov 15, 2016 at 5:05
  • Ohk Sir thanku,how can i query to get above result you suggested,as i cant use $concat i am using mongodb 2.8 Commented Nov 15, 2016 at 5:09

1 Answer 1

1

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" 
            } 
        } 
    }}
])
Sign up to request clarification or add additional context in comments.

6 Comments

Why my hobbies field at top [ {'hobbies': ['Football', 'Cricket' ] , 'name': 'Sam', 'age': 20 }]
i want it at last
For that do i need to add another projection stage?
@Parshuram I have the correct order. Modify the order in which properties are displayed in MongoDB. You can always do this since you need a client side processing. What is your language driver?
I am using nodejs,and now i am playing in robomongo its not giving me proper order as per my $project stage
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.