databasemongodbmongodb-querynosqlobject-oriented-database

How do I nest an existing key-value pair inside another object in Mongodb?


I have a collection with multiple documents inside Mongodb. The document in this collection looks like -

{
    "name": "xyz",
    "address": "abc",
    "phone": "100"
}

I wish to move some key-value pairs into another object in the same document. So, the final document looks like -

{
    "name": "xyz",
    "details": {
        "address": "abc",
        "phone": 100
    }
}

How do I achieve this?


Solution

  • try this:

    db.collection.updateMany(
        {},
        {
            $rename: {
                "address": "details.address",
                "phone": "details.phone"
            }
        })