简体   繁体   中英

$set does not change the value of the field in java driver for mongodb

My collection is something like this:

{
"_id" : ObjectId("597c4c42398593a7b464fc9c"),
"userId" : NumberLong(2),
"steps" : [ 
    {
        "_id" : ObjectId("597c4c42398593a7b464fc9a"),
        "beginningDate" : "2017-07-29T13:20:10.344",
        "state" : "Pending",
        "messages" : [ 
            {
                "_id" : ObjectId("597c4c42398593a7b464fc9b"),
                "content" : "Hi",
                "isRead" : 0,
                "side" : "UserToAdmin",
                "creationDate" : "2017-07-29T13:20:10.344"
            }
        ]
    }, 
    {
        "_id" : ObjectId("597c4ce5398593aaa897ccb4"),
        "beginningDate" : "2017-07-29T13:22:53.884",
        "state" : "Open",
        "messages" : []
    }
],
"lastStepState" : "Pending",
"lastModified" : "2017-07-29T13:26:36.774"
}

What I'm basically trying to do is whenever I push a new step into the steps array, I update the lastStepState in the following way:

Document updateQueryDoc = new Document("userId", userId).append("lastStepState",
                new Document("$eq", State.Pending.name()));
        Document updateDoc = new Document("$push", new Document("steps", newStepDoc))
                .append("$set", new Document("lastStepState", State.Open.name()))
                .append("$set", new Document("lastModified", now));

(State is an enum with Pending and Open values) However, the lastStepState does not gets updated. what could be the problem? (I also should mention that there is one document in the collection, so using updateMany is not a soultion to my problem.)

Document's append uses the underlying Map's put(K key, V value) function, so when you call append("$set", new Document("lastModified", now)) it overwrites the value of the previously set $set key.

You can fix it like this:

Document updateDoc = new Document("$push", new Document("steps", newStepDoc))
    .append("$set", new Document("lastStepState", State.Open.name()).append("lastModified", now));

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