【问题标题】:Updating JSON Object in Mongodb using spring boot使用 Spring Boot 在 Mongodb 中更新 JSON 对象
【发布时间】:2021-12-28 07:32:43
【问题描述】:

假设我有一个需要在 Mongodb 中更新的 JSON 对象

{
  "_id": 12345,
  "Attribute": { "Property1": "X", "Property2": true, "Property3": 123 }
}

假设我在 mongoDb 中有一条记录

{
    "_id": 12345,
    "Attribute1": "abc",
    "Attribute2": "xyz",
    "Attribute": { "Property4": "X", "Property2": false, "Property3": 456 }
}

结果应更新属性 JSON,同时仅更新已更改的字段并保持其余值不变。 db 中的结果记录应该是这样的

{
    "_id": 12345,
    "Attribute1": "abc",
    "Attribute2": "xyz",
    "Attribute": { "Property4": "X", "Property1": "X", "Property2": true, "Property3": 123 }
}

我真的不知道如何在 Mongodb 中使用 JAVA spring boot 来实现这一点。有人可以帮忙吗?任何帮助表示赞赏。

【问题讨论】:

  • 简单的 "$set" 将完成预期的工作。

标签: java mongodb spring-boot


【解决方案1】:

您可以使用 org.springframework.data.mongodb.core.query 包中的更新类。您可以编写如下代码 sn-p。

Update updateAttribute = new Update();
      updateAttribute.push("Attribute", "Your Value");
      mongoOperations.updateFirst(new Query(Criteria.where("id").is(12345)), updateAttribute, "yourCollection");

另外,您需要从 org.springframework.data.mongodb.core 包中为 MongoOperations 注入构造函数。

【讨论】:

    【解决方案2】:

    你可以通过两种方式做到这一点,

    1. 对于 Mongo 4.4+ 版本,您可以使用 pipelined updates,这允许在更新正文中使用聚合运算符,特别是我们希望使用 $mergeObjects,如下所示:
    db.collection.update(
    {
      _id: 12345
    },
    [
      {
        $set: {
          Attribute: {
            $mergeObjects: [
              "$Attribute",
              {
                "Property1": "X",
                "Property2": true,
                "Property3": 123
              }
            ]
          }
        }
      }
    ])
    

    Mongo Playground

    1. 对于较小的 Mongo 版本,您必须在代码中构建更新主体,这是一个 javascript 示例(在春季可能会更烦人)
    const input = {
        '_id': 12345,
        'Attribute': { 'Property1': 'X', 'Property2': true, 'Property3': 123 },
    };
    
    const updateBody = {};
    Object.keys(input.Attribute).forEach((key) => {
        const updateKey = `Attribute.${key}`;
        updateBody[updateKey] = input.Attribute[key];
    });
    db.collection.updateOne({ _id: 12345 }, { $set: updateBody });
    

    通过在更新正文中使用点表示法,我们确保不会覆盖 Attribute 中的现有字段。

    【讨论】:

    • 谢谢你,但是一个简单的“$set”也可以。
    • 这是一个简单的集合。
    【解决方案3】:

    我使用这个查询实现了这一点。

    db.collection.update(
        {
          _id: 12345
        },
          {
            $set: {
                  
                    "Property1": "X", 
                    "Property2": true, 
                    "Property3": 123 
                   }
                
          },
          {upsert: true}
         )
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-01
    • 1970-01-01
    • 2022-01-21
    • 2018-01-26
    • 1970-01-01
    • 2023-02-16
    • 1970-01-01
    相关资源
    最近更新 更多