簡體   English   中英

$ set不會更改mongodb的Java驅動程序中字段的值

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

我的收藏是這樣的:

{
"_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"
}

我基本上想做的是,每當我將新步驟推入步驟數組時,都以以下方式更新lastStepState:

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));

(狀態是具有Pending和Open值的枚舉)。但是,lastStepState不會更新。 可能是什么問題呢? (我還應該提到集合中只有一個文檔,因此使用updateMany並不是解決我的問題的靈丹妙葯。)

Document的append使用基礎Map的put(K key, V value)函數,因此,當您調用append("$set", new Document("lastModified", now))它將覆蓋先前設置的$set鍵的值。

您可以這樣解決:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM