4

I have data in mongoDB like below

{
  "_id": ObjectId("57c40e405e62b1f02c445ccc"),
  "sharedPersonId": ObjectId("570dec75cf30bf4c09679deb"),
  "notificationDetails": [
     {
       "userId": "57443657ee5b5ccc30c4e6f8",
       "userName": "Kevin",
       "isRed": true 
     } 
   ] 
}

Now i want to update isRed value as false How to write query for this. I have tried something like below

var updateIsRedField = function(db, callback) {
    db.collection('notifications').update({_id:notificationId},
    {
        $set: { "notificationDetails.$": {isRed: false}},
    }, function(err, results) {
        callback();
    });
};

MongoClient.connect(config.database, function(err, db) {
    assert.equal(null, err);
    updateIsRedField(db, function() {
        db.close();
    });
    return res.json({});
});
4
  • You got any error while updating? Or is not it updated? Commented Aug 29, 2016 at 11:38
  • It is not updated. Commented Aug 29, 2016 at 11:40
  • Can you check the output for db.collection('notifications').find({_id:notificationId})? Is it giving any record or not? Commented Aug 29, 2016 at 11:42
  • I am getting result because last time it updates entire notificationDetails array as isRed : false Commented Aug 29, 2016 at 11:46

1 Answer 1

3

Since the positional $ operator acts as a placeholder for the first element that matches the query document, and the array field must appear as part of the query document hence the query { "notificationDetails.isRed": true } is essential to get the $ operator to work properly:

db.collection('notifications').update(
    { "_id": notificationId, "notificationDetails.isRed": true },
    { "$set": { "notificationDetails.$.isRed": false } },
    function(err, results) {
        callback();
    }
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.