Pranav s
Pranav s

Reputation: 164

I need to push an array element into an inner element inside a mongo Db document

My intension is to push an array into the index 'jnl_articles' which is nested deep inside.How can i achieve it using a raw mongodb query. I am using Jessengers mongoDB with laravel framework.

Here is the document:

{
"_id" : ObjectId("5ca70c3c5586e920ba79df59"),
"jnl_volumes" : [
     {
        "volume_name" : 6,
        "jnl_issues" : [ 
            {
                "issue_name" : "1",
                "created_date" : "2019-04-10",
                "jnl_articles" : [],
                "issue_status" : "1"
            }, 
        ]
    }
]

}

Below is the array item that i need to push into:

[
{
    "article_name": "art1",
    "created_date": "2019-04-10",
    "article_order": 1
},
{
    "article_name": "art2",
    "created_date": "2019-04-10",
    "article_order": 2
}

]

The desired result i need to obtain is given below.

  {
    "_id" : ObjectId("5ca70c3c5586e920ba79df59"),
    "jnl_volumes" : [
     {
        "volume_name" : 6,
        "jnl_issues" : [ 
            {
                "issue_name" : "1",
                "created_date" : "2019-04-10",
                "jnl_articles" : [ 
                    {
                        "article_name" : "art1",
                        "created_date" : "2019-04-10",
                        "article_order" : 1
                    }, 
                    {
                        "article_name" : "art2",
                        "created_date" : "2019-04-10",
                        "article_order" : 2
                    }
                ],
                "issue_status" : "1"
            }, 
        ]
    }
]

}

Upvotes: 3

Views: 73

Answers (2)

Kh Munkhbat
Kh Munkhbat

Reputation: 32

Try this:

await table_name.update({
    _id: ObjectId("5ca70c3c5586e920ba79df59")
}, {
    $push: {
        jnl_articles: $each: [{
            object
        }, {
            object
        }]
    }
});

Or

for (const object of array) {
    await table_name.update(
    {_id: ObjectId("5ca70c3c5586e920ba79df59")},
    {$push: { jnl_articles: object } });
}

Upvotes: 1

kmdreko
kmdreko

Reputation: 59952

Assuming you want to push articles to the first issue of the first volume, it'd look like:

{ $push: { "jnl_volumes.0.jnl_issues.0.jnl_articles": { $each: [] } } }
// use first volume ----^            ^                  ^      ^
// use first issue ------------------/                  |      |
// use $each to append an array of elements ------------/      |
// your array of articles -------------------------------------/

Documentation for $push and $each.

Upvotes: 1

Related Questions