$set in MongoDB : Not working as intended

2019-08-26 08:42发布

问题:

I have the following document in my DB :

{
....
"key": "val1",
....
"array" :[
{
"k":"v1",
"rejected":"0"

},
{
"k":"v2",
"rejected":"0"

}

]
.....
}

Now basically I want to set "rejected":"1" for ("key":"val1" && array[i]."k":"v1" ).

The API call that I have written is :

var val1="val1";
var v1="v1";

    request.put('https://api.mlab.com/api/1/databases/DB/collections/doc?q={"key": "'+val1+'","array.k":"'+v1+'"}&apiKey=.....',
                        { json: { "$set": {"rejected": "1"}
                        } },
                        function (error, response, body) {
                            if (!error && response.statusCode == 200) {
                                console.log("----->Insertion"+body);
                                return res.status(200).send("[{\"status\":\"success\"}]");
                            }
                            else
                            {console.log(JSON.stringify(response));}
                        });

But the API instead of editing the needed field,it appends a new field at the end of document:

 {
    ....
    "key": "val1",
    ....
    "array" :[
    {
    "k":"v1",
    "rejected":"0"

    },
    {
    "k":"v2",
    "rejected":"0"

    }

    ]
    .....

    "rejected":"1"
    }

回答1:

In this case use db.collection.update

Mongodb shell query

If there is only one matching document

db.collection_name.update(
  {key:"val1", "array.k":"v1"},
  {$set:{"array.$.rejected":"1"}}      
);

If there are multiple documents matching the criteria then use the below query with multi:true

db.collection_name.update(
  {key:"val1", "array.k":"v1"},
  {$set:{"array.$.rejected":"1"}}, 
  {multi:true}
);

Update query has three parts

First is the matching part where we have to give

"key":"val1" and "array.k": "v1"

Second part is to set the updated value

Using $set and positional operator, set the value to be updated here for matching array.k update rejected as "1"

Final part is to specify if multiple documents are matching the criteria then update all the matching documents



回答2:

Let say your json object is called as array...read about positional operator in mongodb.Then this will update your array element

Object.update(
  {'array.key': val1},
  {$set: {'array.$. rejected': 1}},
  function(err, count) { ... });