【问题标题】:Updating / Replacing a deeply nested object in mongodb with spring data mongodb用spring数据mongodb更新/替换mongodb中的深层嵌套对象
【发布时间】:2018-05-21 19:56:42
【问题描述】:

我有一份这样的文件。

{
  "id": "5a212b985735dd44089e4782",
  "people": [
    {
      "personId": "5a212b985735dd44089e4783",
      "name": "Ronaldo",
      "parents": [
        {
          "parentId": "5a212b985735dd44089e4784",
          "name": "Messi",
          "address": [
            {
              "addressId": "5a212b985735dd44089e4785",
              "country": "Argentina",
              "city": "Blah Blah"
            },
            {
              "addressId": "5a212b985735dd44089e4786",
              "country": "USA",
              "city": "New York"
            }
          ]
        }
      ]
    }
  ]
}

我必须将 parents 数组中现有的 parent 对象替换为新的 parent 对象。

我写的代码是:

Query query = new Query(Criteria.where("id").is("5a212b985735dd44089e4782"));
Update update = new Update().push("people.$.parents", parent);
this.mongoTemplate.findAndModify(query, update, PeopleInfo.class);

但是,它不是替换现有的 parent 对象,而是创建一个新对象。

有谁知道如何执行这种查询?

【问题讨论】:

  • 3.6 支持多位置运算符。您可以在 shell 中尝试db.collection_name.update( {_id: "5a212b985735dd44089e4782" }, { $set: { "people.$[p].parents.$[pp]": parent } }, { arrayFilters: [ { 'p.name': "Ronaldo" }, { "pp.name": "Messi" } ] } )。更多信息here

标签: arrays mongodb spring-data spring-data-mongodb mongotemplate


【解决方案1】:

请阅读 push here 的文档。在这种情况下你应该做的是set 而不是push

Query query = new Query(Criteria.where("id").is("5a212b985735dd44089e4782"));
Update update = new Update().set("people.parents", parent);
this.mongoTemplate.findAndModify(query, update, PeopleInfo.class);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-13
    • 2019-02-17
    • 2021-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多