简体   繁体   中英

Mongodb - update specific array element

I have a collection "prefs" with document structure as below

{
    _id: {
        userId: "abc"
    },
    val: {
        status: 1,
        prefs: [
            {
                value: "condition",
                lastSent: ISODate("2017-07-17T23:46:53.717Z")
            }
        ],
        deal: 2,
        prevDeal: 3
    }
}

I am trying to update the date field lastSent with a condition on userId and status. Below are the queries that I derieved from my Java code.

Select Query:

{ "_id" : { "userId" : "abc"} , "val.status" : 1 , "val.prefs.value" : "condition"}

Update Query:

{ "$set" : { "val.prefs.$.lastSent" : { "$date" : "2017-07-17T23:50:07.009Z"}}}

The above query is giving error as follows:

The dotted field 'prefs.$.lastSent' in 'val.prefs.$.lastSent' is not valid for storage.

How do I achieve this?

Below is my Java code:

BasicDBObject _idObject = new BasicDBObject();
_idObject.put("userId", "abc");

BasicDBObject _selectQuery = new BasicDBObject();
_selectQuery.put("_id", _idObject);
_selectQuery.put("val.status", 1);
_selectQuery.put("val.prefs.value", "condition");

BasicDBObject _valueUpdateQuery = new BasicDBObject();
_valueUpdateQuery.put("prefs.$.lastSent", lastSent);

BasicDBObject _updateQuery = new BasicDBObject();
_updateQuery.put("$set", new BasicDBObject("val", _valueUpdateQuery));

prefs.update(_selectQuery, _updateQuery, true, true);

I just tested with your code in mongo shell this codes works fine you don't have to mention

$date

and i used this code for updating date

db.getCollection('tester').update({ "_id" : { "userId" : "abc"} , "val.status" : 1 , "val.prefs.value" : "condition"},{ "$set" : { "val.prefs.$.lastSent" : new Date()}})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM