【发布时间】:2021-02-24 13:54:09
【问题描述】:
我在 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();
当我运行此代码时,它会添加全新的项目,删除所有项目。如何更新特定字段。
【问题讨论】: