增加元素数组中的字段的值

时间:2019-01-16 19:17:24

标签: mongodb spring-data-mongodb

我的收藏集中的文件具有以下结构:

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

我想在我的CollectionRepository中有一个方法,该方法通过将方法的collection ID和arrayField中元素的字段ID赋予该方法来增加字段计数的值。

我感觉无法通过方法名称使用Spring Data自动生成的查询来做到这一点。

因此,我尝试使用@Query注释执行此操作,但是我不知道如何执行此操作,因为我需要根据_id选择集合,然后根据id选择数组中的字段,然后将计数增加一。有提示吗?

1 个答案:

答案 0 :(得分:1)

对不起,很抱歉,这是您的问题的解决方案。

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

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

承认您正在使用MongoDB服务器和MongoDB Java Driver 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数据方法签名不太可能生成此更新。我建议您使用CustomCollectionRepository扩展一个CollectionRepository接口。您可以在此接口中定义此更新方法签名,并在CustomCollectionRepositoryImpl类中实现它。请找到提到该解决方案的part of the documentation

相关问题