skip to Main Content

I have an array of objects and would like to update the count of the object where categoryId = "menu2" and subCategoryId = "1".

in my mongodb i currently have two records in the array:

{
    "_id": "xyz",
    "badges": [{
        "count": 2,
        "categorieId": "menu1",
        "subCategorieId": "1"
    }, {
        "count": 1,
        "categorieId": "menu2",
        "subCategorieId": "1"
    }]
}

if i now execute the following method the object with categorieId "menu1" will be updated and not my menu2…

return getCollection()
      .updateOne(
        and(
          eq("badges.categorieId", "menu2"),
          eq("badges.subCategorieId", "1")
        ),
        Updates.inc("badges.$.count", 1)
      );

I am using the io.quarkus.mongodb.reactive.ReactiveMongoCollection.

Thanks in advance!

2

Answers


  1. Chosen as BEST ANSWER

    The filtered positional operator is working:

    return getCollection().updateOne(
          eq("_id", "xyz"),
          Updates.combine(
            Updates.inc("badges.$[badges].count", 1)
          ),
          new UpdateOptions()
            .arrayFilters(Arrays.asList(
              and(
                eq("badges.categorieId", "menu2"),
                eq("badges.subCategorieId", "1")
              ))));
    

    Why the other method does not work, i unfortunately do not know.


  2. You could use the "$[]" array update operator to update all the matching elements in the array. In your case it will be something like this:

    Updates.inc("badges.$[].count",1)
    

    More details on the official MongoDB documentation

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search