Mongo 模板的 findAndModify 正在为添加或更新嵌套元素返回空值

Mongo Template's findAndModify is returning null values for adding or updating nested elements

我的数据格式为:

{
    "_id" : "149",
    "books" : {
       "32" : "0.12",
       "33" : "0.21"
    }
}

我想在嵌套的 books 文档中 update/insert 值。如果我插入一个新行说 "39" : "0.19",那么更新后的文档应该如下所示:

{
    "_id" : "149",
    "books" : {
       "32" : "0.12",
       "33" : "0.21",
       "39" : "0.19"
    }
}

并且更新应该可以正常工作,按照它们应有的方式工作。通过更新值。

我尝试了几种方法,但无法按照我想要的方式更新。

方法1:有效但结果错误

MongoCollection<Document> document =  mongoTemplate.getCollection("booksCollection");

BasicDBObject query = new BasicDBObject();
query.put("_id", storeId);

BasicDBObject bookDiscount = new BasicDBObject();
bookDiscount.put(bookId, discount);

BasicDBObject update = new BasicDBObject();
update.put('$push', new BasicDBObject("books", bookDiscount));

document.findOneAndUpdate(query, update);

方法 1 输出:每个值都添加到新行中

{
    "_id" : "1664",
    "books" : [ 
        {
            "28" : NumberDecimal("0.75")
        }, 
        {
            "29" : NumberDecimal("0.18")
        }, 
        {
            "30" : NumberDecimal("0.23")
        }, 
        {
            "245" : NumberDecimal("0.26")
        }, 
        {
            "277" : NumberDecimal("0.13")
        }, 
        {
            "270" : NumberDecimal("0.19")
        }
    ]
}

方法2:有效但结果错误

MongoCollection<Document> document =  mongoTemplate.getCollection("booksCollection");

BasicDBObject query = new BasicDBObject();
query.put("_id", storeId);

BasicDBObject bookDiscount = new BasicDBObject();
bookDiscount.put(bookId, discount);

BasicDBObject update = new BasicDBObject();
update.put('$set', new BasicDBObject("books", bookDiscount));

document.findOneAndUpdate(query, update);

方法 2 输出:值总是被替换

{
    "_id" : "16644158",
    "locationInfRate" : {
        "2857" : NumberDecimal("0.68")
    },
    "_class" : "com.test.books"
}

我学到了什么:

$push 方法将数据推送为列表的成员。 $set 方法更新数据,但对于地图,如果查询中的地图格式不正确,它会替换数据。

我将 $set 查询编辑为以下格式并且有效:

MongoCollection<Document> document =  mongoTemplate.getCollection("booksCollection");

BasicDBObject query = new BasicDBObject();
query.put("_id", storeId);

BasicDBObject bookDiscount = new BasicDBObject();
bookDiscount.put("books." + bookId, discount);

update.put('$set', bookDiscount);

document.findOneAndUpdate(query, update);