代码之家  ›  专栏  ›  技术社区  ›  neeeextL

更新数组对象mongoDB

  •  0
  • neeeextL  · 技术社区  · 3 年前

    我有一个对象数组,希望更新categoryId=“menu2”和subCategoryId=“1”所在对象的计数。

    在我的mongodb中,阵列中目前有两条记录:

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

    如果我现在执行以下方法,则带有categorieId“menu1”的对象将被更新,而不是我的menu2。。。

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

    我正在使用io。夸克斯。mongodb。反应性。反应性MongoCollection。

    提前谢谢!

    0 回复  |  直到 3 年前
        1
  •  0
  •   Mysticboi    3 年前

    可以使用“$[]”数组更新运算符更新数组中的所有匹配元素。在你的情况下,它将是这样的:

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

    关于官方的更多细节 MongoDB documentation

        2
  •  0
  •   neeeextL    3 年前

    过滤后的位置操作符正在工作:

    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")
              ))));
    

    不幸的是,我不知道为什么其他方法不起作用。