首页 > 解决方案 > 如何使用存储库模式更新 mongodb 中的嵌入文档

问题描述

如何使用 Spring Data Repository 更新 MongoDB 中的嵌入式文档。

[{
    "_id": 1,
    "hotel_name": "test_hotel",
    "reviews": [

      {
        "id": 1,
        "rating": "4star",
        "username": "test_user"
      },
      {
        "id": 2,
        "rating": "4star",
        "username": "test_user"
      },
      {
        "id": 3,
        "rating": "4star",
        "username": "test_user"
      }
    ]

  },
  {
    "_id": 2,
    "hotel_name": "test_hotel2",
    "reviews": [

      {
        "id": 1,
        "rating": "4star",
        "username": "test_user"
      },
      {
        "id": 2,
        "rating": "4star",
        "username": "test_user"
      },
      {
        "id": 3,
        "rating": "4star",
        "username": "test_user"
      }
    ]

  }
]

例如,在上面的 json 中,我想更新第二家酒店,查看 id 2。请你帮我如何实现这个需求的存储库。谢谢。

标签: javamongodbspring-boot

解决方案


使用spring stack,你可以使用SpringData来做,你只需要实现一个扩展MongoRepository的接口并使用Update类进行更新。

我找到了一个详细的快速入门示例: https ://www.baeldung.com/spring-data-mongodb-tutorial


推荐阅读