简体   繁体   中英

Update array object mongoDB

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!

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM