0

I have data like below

> db.user.find().pretty().limit(1);
{
        "_id" : ObjectId("59a7ead6d122a2332e1eb164"),
        "name" : "Jack",
        "status" : "VERIFIED",
        "attributes" : [
                {
                        "value" : "vijay jha",
                        "name" : "patient",
                        "key1" : "",
                        "key2" : "",
                        "key3" : ""
                },
                {
                        "value" : "",
                        "name" : "notes",
                        "key1" : "",
                        "key2" : "",
                        "key3" : ""
                },
                {
                        "value" : "Thomas",
                        "name" : "surgeon",
                        "key1" : "",
                        "key2" : "",
                        "key3" : ""
                }
        ]
}

I am trying to write query to get output like below , I am trying to use unwind but that is producing incorrect result

{  
   "_id":ObjectId("59a7ead6d122a2332e1eb164"),
   "name":"Jack",
   "status":"VERIFIED",
   "patient":"vijay jha",
   "notes":"",
   "surgeon":"Thomas"
}
5
  • @Neil Lunn : I converted the query , it is throwing error db.user.aggregate([ { "$replaceRoot": { "newRoot": { "$arrayToObject": { "$concatArrays": [ [{ "k": "_id", "v": "$_id" }], { "$map": { "input": "$attributes", "in": { "k": "$$this.name", "v": "$$this.value" } }} ] } } }} ]) Commented Sep 1, 2017 at 6:44
  • Which error exactly? Perhaps the one telling you that $arrayToObject is not supported? Go back and read the nice answer again. Commented Sep 1, 2017 at 6:46
  • I am using 3.4.7 , and the error message is "errmsg" : "'newRoot' expression must evaluate to an object, but resulting value was: null. Type of resulting value: 'null'. Input document: {_id: 59a7ead6d122a2332e1eb166}", Commented Sep 1, 2017 at 6:50
  • It looks like we always require the attributes array for each document. I may have lot of documents without this array. Commented Sep 1, 2017 at 6:54
  • Then exclude them from processing. Add a $match and use $exists. Now say thankyou. Commented Sep 1, 2017 at 6:56

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.