Fork me on GitHub

MongoDB 批量更新数组内嵌套的对象

如以下一个文档,筛选出son.id=2的子文档,并将其name值改为change

{
  name: '嘎嘎', arr: [
    {
      oathKey: 'abc',
      son: {
        id: 1,
        name: '456'
      }
    },
    {
      oathKey: 'bcd',
      son: {
        id: 2,
        name: '4567'
      }
    }
  ]
}

利用$占位符进行处理更新,以下是完整的可执行案例:

const mongoose = require('mongoose')
const fs = require('fs')

mongoose.connect('mongodb://localhost/test', { useUnifiedTopology: true, useNewUrlParser: true })
const Temp = mongoose.model('User', new mongoose.Schema({
  name: String,
  arr: [{
    type: Object
  }]
}), 'test_temp');

(async function () {
  await Temp.deleteMany({})
  await new Temp({
    name: '嘎嘎', arr: [
      {
        oathKey: 'abc',
        son: {
          id: 1,
          name: '456'
        }
      },
      {
        oathKey: 'bcd',
        son: {
          id: 2,
          name: '4567'
        }
      }
    ]
  }).save()
  await Temp.updateMany({ 'arr.son.id': 1 }, { $set: { 'arr.$.son.name': 'change' } })
  const res = await Temp.find()
  fs.writeFileSync('./res.json', JSON.stringify(res))
  mongoose.disconnect()
}()).catch(err => {
  console.error(err)
  mongoose.disconnect()
})

输出:

[
  {
    "arr": [
      {
        "name": "abc",
        "son": {
          "id": 1,
          "sonName": "change"
        }
      },
      {
        "name": "bcd",
        "son": {
          "id": 2,
          "sonName": "4567"
        }
      }
    ],
    "_id": "5dce07b972fb2524788e7006",
    "name": "嘎嘎",
    "__v": 0
  }
]