1

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.

2 Answers 2

2

You can achieve this via $project aggregation. It should be something like this:

{ $project: { "$data.name": "$data" } }
Sign up to request clarification or add additional context in comments.

Comments

0

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"
            }
          ]
        ]
      }
    }
  }
])

Mongo Playground

Comments

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.