Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Pull Out nested Objects in Mongodb?

I'm trying to make a query by merging from another collection, but there are obstacles when the query is run, the data generated is not what I imagined

i have the data like this

{
        "_id": "5ce8981a46039c14a4ec32d1",
        "name": "Monkey D Luffy",
        "email": "[email protected]",
        "status": "not verified",
        "password": "$2a$10$ayluBIsOOelBTIk.69GjHubgQemr6dJfgBUELNusCOaUGLpS/qKs6",
        "metas": {
            "role": "admin",
            "smartphone": "ios",
            "address": "konoha",
            "hobby": "eat ramen"
        }
    },

and i want pull out metas from nested document :

{
        "_id": "5ce8981a46039c14a4ec32d1",
        "name": "Monkey D Luffy",
        "email": "[email protected]",
        "status": "not verified",
        "password": "$2a$10$ayluBIsOOelBTIk.69GjHubgQemr6dJfgBUELNusCOaUGLpS/qKs6",
        "role": "admin",
        "smartphone": "ios",
        "address": "konoha",
        "hobby": "eat ramen"
    },

if any duplicate from my question pls suggest me, because I didn't find the same question, mostly using arrays.

and here is my query:

db.accounts.aggregate([
    {
        $lookup: {
            from: "account_meta",
            localField: "_id", 
            foreignField: "account_id",
            as: "metas"
        }
    },

    { "$unwind": "$metas" },
    {
        $group: {
            _id: "$_id",
            name: {$first:"$name"},
            status: {$first: "$status"},
            email: {$first: "$email"},
            password: {$first: "$password"},
            data: {
                "$push": {
                    "k" : "$metas.key",
                    "v": "$metas.value"
                }
            }
        }
    },
    {
        $project: {
            "_id": "$_id", 
            "name": "$name", 
            "email": "$email", 
            "status": "$status", 
            "password": "$password",
            "metas" :{
                $arrayToObject: "$data"
            }
        }
    },
    {
        "$replaceRoot": {

            "newRoot":

                {
                    "$mergeObjects": [ {$arrayToObject: "$data"}, "$$ROOT"]
                },

        }
    },
])
like image 509
Heru Wijayanto Avatar asked Oct 16 '22 14:10

Heru Wijayanto


1 Answers

i just edit some code from my $mergeObject:

{
        "$replaceRoot": {

            "newRoot":

                {
                    "$mergeObjects": [ "$metas", "$$ROOT"]
                },

        }
},
{$project: { metas: 0} }
like image 53
Heru Wijayanto Avatar answered Nov 01 '22 12:11

Heru Wijayanto