Document 1:
{
"data": {
"id": "123456",
"name": "abc",
"value": 1
}
}
Expected Output-
{
"abc": {
"id": "123456",
"name": "abc",
"value": 1
}
}
Explanation: How we can replace the root with the " name" value, check the expected output, whatever value of the "name", it becomes on the root level. and I have multiple documents.
Thanks in advance.
You can achieve this via $project aggregation. It should be something like this:
{ $project: { "$data.name": "$data" } }
Mongo doesn't allow field names to start with a $ meaning you can't define a dynamic key name.
You'll have to work around this restriction by playing with the data structure, here is an example of how to achieve this with $arrayToObject
db.collection.aggregate([
{
"$replaceRoot": {
"newRoot": {
"$arrayToObject": [
[
{
k: "$data.name",
v: "$data"
}
]
]
}
}
}
])