Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

mongodb aggregate flatten resultat

db.collection.aggregate([
              ....
    { $group: {_id: "$data.r.id", "col": {$first: "$data.r"}}},
    {$project:{"o":{"$objectToArray":"$col"}}},
    {$unwind:"$o"},
    {$group:{"_id":null, "keys":{$addToSet:"$o.k"}}},
    {$project: {"keys":1, "_id": 0}},
    {$addFields: {res:{$map:{ input:"$keys", as: "a", in: {"_id":0,"label": "$$a"}}}}},
    {$project: {"res":1}}
])

With my mongodb query the output is:

{ 
"res" : [
    {
        "_id" : 0.0, 
        "label" : "aaaa"
    }, 
    {
        "_id" : 0.0, 
        "label" : "bbbbb"
    }, 
    {
        "_id" : 0.0, 
        "label" : "ccccc"
    }
] }

and i try to output this

        {
            "_id" : 0.0, 
            "label" : "aaaa"
        }, 
        {
            "_id" : 0.0, 
            "label" : "bbbb"
        }, 
        {
            "_id" : 0.0, 
            "label" : "cccc"
        }
    

so i added

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{$replaceRoot : {"newRoot": "$res"}}

but i got this error

”newRoot’ expression must evaluate to an object, but resulting value
was: [{_id: 0, label: "aaaa"},{_id: 0, label: "bbbb"},{_id: 0, label:
"cccc"}]

How can i remove the uselesss nested object "res" to return only the list/array of object(id,label) ?

>Solution :

Re-write the answer from the comment to resolve the question.

You need to flatten the deconstruct res array first

{ $unwind: "$res" }

before replacing the input documents with

{
  $replaceRoot: {
    newRoot: "$res"
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading