Insert Into Array of object MongoDB

2019-06-07 06:47发布

问题:

I have

{
    "_id" : ObjectId("5a25af80d2c4dd065991dccc"),
    "username" : "abc@gmail.com",
    "password" : "$2a$10$ptFyLKtyyrL5gMYdXS6wV.HLUA4Py5iudMJDldf5qsHFS4.9TPCyy",
    "role" : "Admin",
    "__v" : 0,
    "list" : [ 
        {
            "name" : "We",
            "arr" : [ 
                "5a26d554677475818a795f75", 
                "5a395bb0976d5304c07f7dd4"
            ]
        }, 
        {
            "name" : "sandeep",
            "arr" : [ 
                "5a26d554677475818a795f75"
            ]
        }
    ]
}

I want to add an element inside list.arr where name = 'we' and add only if the element does not exist

how do i perform this query.

回答1:

if i properly understood you question,you want to match name field with we key,and update arr only if it exists ?, you have to use elemMatch, in other to get the right document

db.test.update({ list: { $elemMatch: { name: "We" , arr: { $nin: [ "valuette" ] }} } }, {  $push: { "list.$.arr": "valuette" } } );

the $ in "list.$.arr" matches the specified index that matches name field with we value

update: to answer OP question



回答2:

Intial database structure

> db.collection.find().pretty()
{
    "_id" : ObjectId("5a25af80d2c4dd065991dccc"),
    "username" : "abc@gmail.com",
    "password" : "$2a$10$ptFyLKtyyrL5gMYdXS6wV.HLUA4Py5iudMJDldf5qsHFS4.9TPCyy",
    "role" : "Admin",
    "__v" : 0,
    "list" : [
        {
            "name" : "We",
            "arr" : [
                "5a26d554677475818a795f75",
                "5a395bb0976d5304c07f7dd4"
            ]
        },
        {
            "name" : "sandeep",
            "arr" : [
                "5a26d554677475818a795f75"
            ]
        }
    ]
}

Query executed

> db.collection.update({ list: { $elemMatch: { name: "We" , arr: {$nin: ["55555555555555555"]} } } }, {  $push: { "list.$.arr": "55555555555555555" } } )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

New database structure

> db.collection.find().pretty()
{
    "_id" : ObjectId("5a25af80d2c4dd065991dccc"),
    "username" : "abc@gmail.com",
    "password" : "$2a$10$ptFyLKtyyrL5gMYdXS6wV.HLUA4Py5iudMJDldf5qsHFS4.9TPCyy",
    "role" : "Admin",
    "__v" : 0,
    "list" : [
        {
            "name" : "We",
            "arr" : [
                "5a26d554677475818a795f75",
                "5a395bb0976d5304c07f7dd4",
                "55555555555555555"
            ]
        },
        {
            "name" : "sandeep",
            "arr" : [
                "5a26d554677475818a795f75"
            ]
        }
    ]
}

Again same query Executed

> db.collection.update({ list: { $elemMatch: { name: "We" , arr: {$nin: ["55555555555555555"]} } } }, {  $push: { "list.$.arr": "55555555555555555" } } )
WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 })

Checking the database structure again

> db.collection.find().pretty()
{
    "_id" : ObjectId("5a25af80d2c4dd065991dccc"),
    "username" : "abc@gmail.com",
    "password" : "$2a$10$ptFyLKtyyrL5gMYdXS6wV.HLUA4Py5iudMJDldf5qsHFS4.9TPCyy",
    "role" : "Admin",
    "__v" : 0,
    "list" : [
        {
            "name" : "We",
            "arr" : [
                "5a26d554677475818a795f75",
                "5a395bb0976d5304c07f7dd4",
                "55555555555555555"
            ]
        },
        {
            "name" : "sandeep",
            "arr" : [
                "5a26d554677475818a795f75"
            ]
        }
    ]
}

No changes Found



回答3:

By using this nested query I solved this problem. I'm doing it with Node JS

router.post('/prevList', (req, res) => {
  User.update({'_id':req.user.id, list: { $elemMatch: { name: req.body.name } } },{  $addToSet: { "list.$.arr": {$each: req.body.arr} } },function(err,data) {
    console.log(data);
    res.send(data)
  });
});

Here

req.body: {name:'we',arr:["5a395bb0976d5304c07f7dd4"]}

and req.user.id is the auth id.

Hope this helps you all too.