首页 > 解决方案 > 使用 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();

当我运行此代码时,它会添加全新的项目,删除所有项目。如何更新特定字段。

标签: javamongodbmicronaut

解决方案


在做了一些研究之后,我发现位置 $ 运算符标识数组中要更新的元素,而无需明确指定数组中元素的位置。

现在文档代码将更改如下

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


推荐阅读