【问题标题】:Updating an item in an embedded document in MongoDB using Java MongoClient使用 Java MongoClient 更新 MongoDB 中嵌入文档中的项目
【发布时间】: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();

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

【问题讨论】:

    标签: java mongodb micronaut


    【解决方案1】:

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

    现在文档代码将更改如下

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-18
      • 2019-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-04
      • 1970-01-01
      相关资源
      最近更新 更多