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
{$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"
}
}