代码之家  ›  专栏  ›  技术社区  ›  javapedia.net

mongodb使用数据库更新()

  •  0
  • javapedia.net  · 技术社区  · 4 年前

    我通过引用相关的stackoverflow答案编译了2个update查询,但是,它似乎不起作用,query更新所有元素,而只更新与条件匹配的元素。

    文件:

    [
      {
        "_id": 259,
        "members": [
          {
            "email": "test1@gmail.com",
            "added_by": "javapedia.net",
            "status": "pending"
          },
          {
            "email": "test2@gmail.com",
            "added_by": "javapedia.net",
            "status": "pending"
          },
          {
            "email": "test3@gmail.com",
            "status": "pending"
          }
        ]
      }
    ]
    

    查询1:使用elemMatch运算符,mongodb: https://mongoplayground.net/p/4cNgWJse86W

    db.collection.update({
      _id: 259,
      "members": {
        "$elemMatch": {
          "email": {
            "$in": [
              "test3@gmail.com",
              "test4@gmail.com"
            ]
          }
        }
      }
    },
    {
      "$set": {
        "members.$[].status": "active"
      }
    },
    {
      "multi": true
    })
    

    https://mongoplayground.net/p/tNu395B2RFx

    db.collection.update({
      _id: 259,
      "members.email": {
        "$in": [
          "test3@gmail.com",
          "test4@gmail.com"
        ]
      }
    },
    {
      "$set": {
        "members.$[].status": "active"
      }
    },
    {
      "multi": true
    })
    

    预期结果:只有一个元素test3@gmail.com状态应更新为活动。

    实际结果:两个查询都更新所有记录。

    1 回复  |  直到 4 年前
        1
  •  1
  •   Minsky    4 年前

    Is this what you're looking for?

    db.collection.update({
      _id: 259,  
    },
    {
      "$set": {
        "members.$[el].status": "active"
      }
    },
    {
      arrayFilters: [
        {
          "el.email": {
            $in: [
              "test3@gmail.com",
              "test4@gmail.com"
            ]
          }
        }
      ]
    })
    
    • 如果需要的话,你可以把初始条件放回去,我只是简短地说(对我来说它们毫无意义)。

    • multi:true 一个文档不需要

    • 也许在语义上使用 updateOne()

    推荐文章