Iron_Man
Iron_Man

Reputation: 161

Unable to set value on object under array

I have a dataset like this

{
    "_id" : ObjectId("5a45f6da3e6de20efc61ecc8"),
    "userid" : "5a20eb5bcdacc7086ce77427",
    "test" : [ 
        {
            "sid" : "5a20ec53cdacc7086ce7742b",
            "sname" : "dev",
            "activity" : "Message",
            "isread" : 0,
            "timestamp" : 1514535070925
        }, 
        {
            "sid" : "5a20ec53cdacc7086ce7742b",
            "sname" : "dev",
            "activity" : "Message",
            "isread" : 0,
            "timestamp" : 1514535356213
        }
    ],
    "__v" : 0
}

Now I am unable to modify the 'isread' value from 0 to 1. What I am writing is:

db.Collection.update({'userid': req.body.userid, 'notifications.timestamp': '1514535356213'}, {$set:{'isread': parseInt(1)}}, {new: true}, function(error, result) {
                        if(error) {
                            console.log(error);
                        } else {
                            console.log(result);
                            //I am getting this result i.e {
                                                           "ok": 0,
                                                           "n": 0,
                                                           "nModified": 0
                                                           }
                        }
                    });

I don't know why my value is not updated. any help is appreciated

Upvotes: 0

Views: 45

Answers (1)

Avij
Avij

Reputation: 694

Try

> db.coll3.update({
    'userid': '5a20eb5bcdacc7086ce77427'
}, {
    $set: {
        'test.$[elem].isread': 1
    }
}, {
    multi: true,
    new: true,
    arrayFilters: [{
            'elem.timestamp': {
                $eq: 1514535356213
            }
        }
    ]
})
WriteResult({
    "nMatched": 1,
    "nUpserted": 0,
    "nModified": 1
})

Using findAndModify

db.coll3.findAndModify({query:{
    'userid': '5a20eb5bcdacc7086ce77427'
}, update:{
    $set: {
        'test.$[elem].isread': 1
    }
}, 
    new: true,
    arrayFilters: [{
            'elem.timestamp': {
                $eq: 1514535356213
            }
        }
    ]
})

There are various ways to do this sort of operations. Hope this helps

Upvotes: 1

Related Questions