简体   繁体   English

使用 Java 向 MongoDB 文档中的列表添加元素

[英]Adding an element to a list in a MongoDB Document using Java

I am a little confused as to how to add an element to an array in an exisiting mongodb document, or why my results are not showing properly and how I expect.我对如何向现有 mongodb 文档中的数组添加元素,或者为什么我的结果没有正确显示以及我期望的方式感到有些困惑。

There is only one document in the collection and will only ever be one.集合中只有一个文档,并且永远只有一个。 The mongo document looks like when I do a db.collection-name.find.pretty() command in a mongo session on the command line:当我在命令行的 mongo 会话中执行db.collection-name.find.pretty()命令时,mongo 文档看起来像:

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

I want to add another object to the calculations list.我想将另一个对象添加到calculations列表中。

The Java code I am running is based upon THIS example:我正在运行的 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));

However when I do a System.out.println(collection.find().first()) in the code after this or db.collection-name.find.pretty() in a mongo session the new document has not been added.但是,当我在此之后的代码中执行System.out.println(collection.find().first())或在 mongo 会话中执行db.collection-name.find.pretty() ,新文档尚未添加。 There are no errors thrown and completes fine.没有抛出错误并且完成得很好。

What I am wondering is我想知道的是

  • Is the line collection.updateOne(new Document("_id", "1234567890"), Updates.push("calculations", newDocument));是行collection.updateOne(new Document("_id", "1234567890"), Updates.push("calculations", newDocument)); correct?正确的?
  • Has it been added but not been saved - if so how do I save?是否已添加但未保存 - 如果是,我该如何保存?
  • Can I do this at a document level, for example document.update(new Documen(Updates.push("calculations", newDocument)); or similar?我可以在文档级别执行此操作吗,例如document.update(new Documen(Updates.push("calculations", newDocument));或类似的?
  • I have also tried collection.findAndUpdateOne(new Document("_id", "1234567890"), Updates.push("calculations", newDocument));我也试过collection.findAndUpdateOne(new Document("_id", "1234567890"), Updates.push("calculations", newDocument)); with the same result结果相同
  • Is how I am getting/hardcoding the document ID incorrect?我如何获取/硬编码文档 ID 不正确?

You have filter condition issue (your _id is ObjectId type)您有过滤条件问题(您的_idObjectId类型)

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

Always make sure your documents updated correctly.始终确保您的文档正确更新。 Look code fagment:看代码片段:

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 https://api.mongodb.com/java/3.1/com/mongodb/client/result/UpdateResult.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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