0

我与 MongoDB 中具有不同城市地址的营销人员有文档。

{
  "_id": "name",
  "cities": [
    {
      "id": "1234abc",
      "city_name": "London",
      "country": "England",
      "addresses": [
        {
          "Home": "Unit 14 Edgar Buildings George Street"
        },
        {
          "Office": "Studio 103 The Business Centre 61"
        }
      ]
    },
    {
      "id": "1234xyz",
      "city_name": "Paris",
      "country": "France",
      "addresses": [
        {
          "Home": "102  rue La Boétie"
        },
        {
          "Office": " IMPASSE VIVALDI VAUCE"
        }
      ]
    }
  ]
}

我的实体类是 Person、city 和 address。
如果该人转移到另一个国家,如 Canda 并想要更新法国 - 巴黎子文档。

{"_id": "name",
{
      "id": "1234xyz",
      "city_name": "Toronto",
      "country": "Canada",
      "addresses": [
        {
          "Home": "Toronto City Hall 100 Queen St W"
        },
        {
          "Office": "4110 Yonge StNorth York, ON M2P 2H3"
        }
      ]
    }
}

我不知道哪个 Spring Data Mongo api 将在这里工作。

我已尝试使用以下代码,但没有任何更新。

Update changed = new Update().pull("cities", new Query(Criteria.where("_id").is(username)));
mongoTemplate.updateFirst(new Query(Criteria.where("cities._id").is(cityId)), changed, Person.class);

如果我使用Update update = new Update().set("cities",city);所有子文档,则替换为一个城市

预期产出

{
  "_id": "name",
  "cities": [
    {
      "id": "1234abc",
      "city_name": "London",
      "country": "England",
      "addresses": [
        {
          "Home": "Unit 14 Edgar Buildings George Street"
        },
        {
          "Office": "Studio 103 The Business Centre 61"
        }
      ]
    },
    {
      "id": "1234xyz",
      "city_name": "Toronto",
      "country": "Canada",
      "addresses": [
        {
          "Home": "Toronto City Hall 100 Queen St W"
        },
        {
          "Office": "4110 Yonge StNorth York, ON M2P 2H3"
        }
      ]
    }
  ]
}
4

3 回答 3

0

要删除特定的城市文档:

Update changed = new Update().pull("cities", new Query(Criteria.where("id").is(cityId)));
mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(username)), changed, Person.class);

添加新的城市信息:

Update update = new Update().addToSet("cities",city);
于 2019-08-04T10:39:27.280 回答
0

请问,你能在这里检查一次吗?Criteria.where("cities._id").is(cityId). 在这里我瘦我们必须使用"cities.id".

于 2019-08-04T05:21:28.787 回答
0

感谢 MrSSharma 和 Ravi 的回答。

现在我正在删除它并在列表中推送更新的文档,而不是更新子文档实体。它对我有用。通过执行 toHexString 访问对象 ID 后。

删除操作 update.pull("cities", Query.query(Criteria.where("id").is(id.toHexString()))); mongoOperations.upsert(查询,更新,Person.class);

添加操作:update.push("cities", subdocumentEntity); mongoOperations.updateFirst(query, update, Person.class));

于 2019-08-09T10:06:39.240 回答