java - 使用 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 会话中执行代码时,尚未添加新文档。没有抛出错误并且可以正常完成。
我想知道的是
- 线路
collection.updateOne(new Document("_id", "1234567890"), Updates.push("calculations", newDocument));
正确吗? - 是否已添加但未保存 - 如果是,我该如何保存?
- 例如,我可以在文档级别执行此操作
document.update(new Documen(Updates.push("calculations", newDocument));
吗? - 我也试过
collection.findAndUpdateOne(new Document("_id", "1234567890"), Updates.push("calculations", newDocument));
同样的结果 - 我获取/硬编码文档 ID 的方式是否不正确?
解决方案
您有过滤条件问题(您的_id
isObjectId
类型)
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
推荐阅读
- react-native - React Native 应用程序中类似 Uber 的抽屉导航
- python - Python嵌套字典在内部比较值
- php - 如何从 Laravel 数据库中的 Products 表中查询卖家 ID
- php - PHP 生成一个从 0 到 36 的数字可能是公平的
- django - 突然我在端点上得到 502,其余工作正常
- python - 解析大型 excel 文件并将结果写回分隔文本文件
- vim - VIM 删除 - 多行
- java - Java - if-else 语句返回假阴性
- r - 需要帮助从 R 中的日期中删除时间模式
- spring - BCryptPasswordEncoder 在升级到 spring secrity 5 后不工作