2

For example, in my Mongo Aggregate request I'm getting the array, which consists of two objects:

[
  {
    "key": "first",
    "meta": 123,
  },
  {
    "key": "second",
    "meta": 567,
    "maybeonmorefield": 789
  }
]

Is it possible to convert this array to the following object by using only Mongo aggregation framework:

{
  "first": {
    "meta": 123,
  },
  "second": {
    "meta": 123,
    "maybeonmorefield": 789
  }
}

As you see, the keys are actually the key field values from the objects in the first examples.

Thanks for any tips :)

0

1 Answer 1

1

You can use $replaceRoot to re-arrange your documents on root level and $arrayToObject to build new keys dynamically:

db.collection.aggregate([
    {
        $addFields: {
            "root": "$$ROOT"
        }
    },
    {
        $project: {
            "root.key": 0,
            "root._id": 0
        }
    },
    {
        $replaceRoot: {
            newRoot: {
                $arrayToObject: [[ { k: "$key", v: "$root" } ]]
            }            
        }
    }
])

Mongo Playground

Sign up to request clarification or add additional context in comments.

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.