增加元素数组中字段的值

Increase value of a field inside an array of element

我的 collection 中有具有以下结构的文档:

{
    "_id": "1234566780",
    "arrayField": [
      {
        "id": "1",
        "count": 3
      },
      {
        "id": "2",
        "count": 5
      }
    ]
}

我想在我的 CollectionRepository 中有一个方法,它通过为方法提供 collection id 和 arrayField 中元素的字段 id 来增加字段计数的值。

我感觉无法使用 Spring 按方法名称自动生成的数据查询。

所以我正在尝试使用@Query 注释来完成它,但我不知道该怎么做,因为我需要 select 基于 _id 的 collection,然后select 数组里面的字段根据id,然后count加一。有什么提示吗?

抱歉耽搁了,这是解决您问题的方法。

您可以使用 arrayFilter 更新选项更新数组的特定元素。 MongoDB 更新操作如下所示:

db.collection.update(
    {"_id":"1234566780"},
    {$inc:{"arrayField.$[elem].count":1}},
    {arrayFilters:[{"elem.id":"2"}]}

承认您正在使用 MongoDB 服务器和 MongoDB java 驱动程序版本 3.6 或更高版本,您可以使用:

public void updateCollection () {
    MongoCollection<Document> collection = mongoTemplate.getDb().getCollection("collection");
    Bson query = new Document("_id", "1234566780");
    Bson update = Updates.inc("arrayField.$[elem].count",1);
    UpdateOptions updateOptions = new UpdateOptions().arrayFilters(Arrays.asList( Filters.eq("elem.id","2")));
    collection.updateOne(query, update, updateOptions);
}

确实 Spring 数据方法签名不太可能生成此更新。我建议您使用 CollectionRepository 扩展 CustomCollectionRepository 接口。您可以在此接口中定义此更新方法签名并在 CustomCollectionRepositoryImpl class 中实现它。请找到提到此解决方案的part of the documentation