如何解决使用 Java MongoClient 更新 MongoDB 中嵌入文档中的项目
我在 mongo db 中有以下数据
{
"_id": "6033c4b184116e3dfdc39d1a","description": "Men description","name": "Men","subCategory": [{
"_id": "60365216fcc02725299e1eb6","name": "This is something I was looking for","description": "This is the description update"
},{
"name": "Sub category 2","description": "Sub category description 2","_id": "6036578cf4c19360225ca2f0"
}
]
}
我想使用如下 mongoDb 的 java 驱动程序更新 subCategory._id = 6036578cf4c19360225ca2f0
Bson query = and(
eq("_id",new ObjectId("6033c4b184116e3dfdc39d1a")),eq("subCategory._id",new ObjectId("6036578cf4c19360225ca2f0"))
);
Document documentList = new Document();
documentList.append(String.format("%s","name"),"name update 1");
documentList.append(String.format("%s","description"),"Description Update 1");
Document document = new Document("$set",new Document("subCategory",List.of(documentList)));
Single.fromPublisher(
this.repository.getCollection(
ConstantValues.PRODUCT_CATEGORY_COLLECTION_NAME,Category.class)
.updateOne(query,document)).subscribe();
当我运行此代码时,它添加了删除所有项目的全新项目。如何更新特定字段。
解决方法
在做了一些研究之后,我发现 位置 $ 运算符标识了数组中要更新的元素,而无需明确指定该元素在数组中的位置。>
现在文档代码将更改如下
Document documentList = new Document();
documentList.append(String.format("%s.$.%s","subCategory","name"),"name update 1");
documentList.append(String.format("%s.$.%s","description"),"Description Update 1");
Document document = new Document("$set",documentList));
参考 - https://riptutorial.com/mongodb/example/22368/update-of-embedded-documents-
https://kb.objectrocket.com/mongo-db/how-to-work-with-embedded-document-in-mongodb-collection-379
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。