java - 使用 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"
}
]
}
我想更新subCategory._id = 6036578cf4c19360225ca2f0
使用 mongoDb 的 java 驱动程序,如下所示
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","subCategory","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
推荐阅读
- regex - 忽略正则表达式中一组数字之间的空格?
- android - Android RecyclerView submitList 未更新 LiveData 观察者中的数据
- java - 重载解析,调用哪个方法
- python - tag_name("a") 中的 "href" 抛出异常
- android - Disabled Rollout Button play console(无灰色勾号):Flutter update app App Bundle Format
- php - 如何将验证 laravel 控制器传递给甜蜜警报 swal
- vim - VIM 无法使用文件的相对路径地址按预期工作
- kubernetes - 气流调度器无法连接到 Kubernetes 服务 api
- signal-processing - 如何将频域图转换为时域图
- r - 如何访问位于列表中的特定列和矩阵行?(在 R 中)