0

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!

neeeextL
  • 1
  • 2
  • Is the problem that you want to update the menu1 record but only menu2 is getting updated? It's hard to tell what your objective is. – nettie Apr 28 '22 at 16:23
  • 1
    @nettie yeah, sorry i updated my question. i want to update categorie "menu2" and subcategorie "1". – neeeextL Apr 29 '22 at 08:10

2 Answers2

0

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

Mysticboi
  • 1
  • 1
  • 2
0

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.

neeeextL
  • 1
  • 2