Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Project values as key and an embedded document as value in mongo

Tags:

mongodb

In mongodb I have a document of structure:

{
    "phone":"123",
    "friends": {
                    "contacts":{
                                    "234":2,
                                    "345":5
                               }
               }
}

I want the output to look like :

{
    "123": {
                "234":2,
                "345":5
           }
}

I have search for multiple solution. Don't seem like getting a solution.

like image 594
Adarsh Trivedi Avatar asked Jan 01 '23 14:01

Adarsh Trivedi


1 Answers

You can use $arrayToObject to create custom keys (takes an array of k-v pairs as a parameter) and then you can use $replaceRoot to get custom root object, try:

db.collection.aggregate([
    {
        $match: {
            phone: { $exists: true },
            "friends.contacts": { $exists: true }
        }
    },
    {
        $addFields: {
            array: [{
                k: "$phone",
                v: "$friends.contacts"
            }]
        }
    },
    {
        $replaceRoot: {
            newRoot: { $arrayToObject: "$array" }
        }
    }
])
like image 134
mickl Avatar answered Jan 05 '23 17:01

mickl