首页 > 解决方案 > 使用 Java 将元素添加到 MongoDB 文档中的列表

问题描述

对于如何将元素添加到现有 mongodb 文档中的数组,或者为什么我的结果没有正确显示以及我的期望如何,我有点困惑。

集合中只有一份文件,而且永远只有一份。当我db.collection-name.find.pretty()在命令行的 mongo 会话中执行命令时,mongo 文档看起来像:

{
    "_id" : ObjectID("1234567890"),
    "details" : {
        ...
    },
    "calculations" : [
        {
            "count" : 1,
            "total" : 10,
            "mean" : 2.5
        },
        {
            "count" : 2,
            "total" : 20,
            "mean" : 6.4
        }
    ]
}

我想将另一个对象添加到calculations列表中。

我正在运行的 Java 代码基于示例:

// Get the database and collection
MongoDatabase database = mongo.getDatabase(dataBaseName);
MongoCollection<Document> collection = database.getCollection(collectionName);
Document document = collection.find().first(); // will only ever be one document 

// The object comes in as a Map
Map<String, Object> incomingMap = new HashMap<>();
incomingMap.put("count", 3);
incomingMap.put("total", 4);
incomingMap.put("mean", 7.9);
// convert to a Document
Document newDocument = new Document();
incomingMap.forEach((k, v) -> {
        newDocument.append(k, v);
});

// append this to the collection - this is where I am confused
// for this example just hardcoding the _id value for simplicity
collection.updateOne(new Document("_id", "1234567890"), Updates.push("calculations", newDocument));

但是,当我System.out.println(collection.find().first())在此之后或db.collection-name.find.pretty()在 mongo 会话中执行代码时,尚未添加新文档。没有抛出错误并且可以正常完成。

我想知道的是

标签: javamongodb

解决方案


您有过滤条件问题(您的_idisObjectId类型)

new Document("_id", ObjectId("1234567890"))`

始终确保您的文档正确更新。查看代码片段:

UpdateResult result = collection.updateOne(filter, update);
log.info("Update with date Status : " + result.wasAcknowledged());
log.info("Nº of Record Modified : "   + result.getModifiedCount());

https://api.mongodb.com/java/3.1/com/mongodb/client/result/UpdateResult.html


推荐阅读