请问如何批量更新合集中所有记录中数组里所有符合条件的元素?
发布于 5 年前 作者 wxie 14230 次浏览 来自 问答

比如说有合集test如下共有2000条记录:

[
  {
    "_id": "1",
    "myArray": [
      {
        "no": 1,
        "status": 0,
        "type": 1
      },
      {
        "no": 2,
        "status": 2,
        "type": 1
      },
      {
        "no": 3,
        "status": 0,
        "type": 2
      },
      {
        "no": 4,
        "status": 0,
        "type": 1
      }
    ]
  },
  {
    "_id": "2",
    "myArray": [
      {
        "no": 1,
        "status": 0,
        "type": 1
      },
      {
        "no": 2,
        "status": 2,
        "type": 1
      },
      {
        "no": 3,
        "status": 0,
        "type": 1
      }
    ]
  },
  {
    "_id": "3",
    "myArray": [
      {
        "no": 1,
        "status": 0,
        "type": 2
      },
      {
        "no": 2,
        "status": 2,
        "type": 1
      },
      {
        "no": 3,
        "status": 0,
        "type": 1
      }
    ]
  },
  ...
  {
   "_id": "2000",
    "myArray": [
      {
        "no": 1,
        "status": 0,
        "type": 1
      },
      {
        "no": 2,
        "status": 1,
        "type": 1
      },
      {
        "no": 3,
        "status": 0,
        "type": 2
      }
    ]
  }
]

需求是把合集里所有记录里data数组中type=1,status=0更新为status=4,请问如何实现?

试了.where().update()都无法实现

使用.aggregate()只能输出聚合结果无法更新内容

db.collection('test')
      .aggregate()
      .project({
        myArray: $.filter({
          input: '$myArray',
          as: 'item',
          cond: $.and([$.eq(['$$item.type',1]), $.eq(['$$item.status', 2])])
        })
      })
      .end()
      .then(res =>{
        console.log(res)
      })
1 回复
db.collection('chatroom').where({
  myArray: _.elemMatch({
    type: 1,
    status: 0,
  })
}).update({
  data: {
    "myArray.$.status": 4,
  }
})

回到顶部