繁体   English   中英

如何在mongodb中使用不同的数据更新某些文档

[英]How can I update some documents with different data in mongodb

如果我具有属于一个大集合的以下文档的ID,并具有一个newBusinessId来更新这些文档。 像这样:

const newBusinessId = '8abc4cef176aa342154d00c0'
const paymentsIds = ['5aba5cef176aa342154d2345', '5aba5cef176aa342154d6789']

这些ID属于我数据库中的以下文档:

[
  {
    _id: '5aba5cef176aa342154d2345',
    state: 'MATURE',
    comment: 'some comment 1',
    startComment: 'some different comment 1',
    expense: 2,
    startExpense: 2,
    businessId: '5aba5cef176aa342154d9876'
  },
  {
    _id: '5aba5cef176aa342154d6789',
    state: 'MATURE',
    comment: 'some comment 2',
    startComment: 'some comment 2',
    expense: 3,
    startExpense: 1,
    businessId: '5aba5cef176aa342154d5432'
  },
]

我想使用相同的businessIdnewBusinessId更新那些文档,并使用INIT的状态值和要使用( startComment,startExpense )值设置的字段( comment,费用以便在更新后可以得到以下结果:

[
  {
    _id: '5aba5cef176aa342154d2345',
    state: 'INIT',
    comment: 'some different comment 1',
    startComment: 'some different comment 1',
    expense: 2,
    startExpense: 2,
    businessId: '8abc4cef176aa342154d00c0'
  },
  {
    _id: '5aba5cef176aa342154d6789',
    state: 'INIT',
    comment: 'some comment 2',
    startComment: 'some comment 2',
    expense: 1,
    startExpense: 1,
    businessId: '8abc4cef176aa342154d00c0'
  },
]

任何想法如何? 我感谢你的强硬!

为了用同一对象中另一个字段的值更新一个字段(例如,费用= startExpense),您必须进行遍历,请尝试以下操作:

yourModel.find().forEach(
    function (elem) {
        yourModel.update(
            {
                _id: { $in: paymentsIds }
            },
            {
                $set: {
                    state : 'INIT',
                    comment : elem.startComment,
                    expense : elem.startExpense,
                    BusinessId : newBusinessId
                }
            }
        );
    }
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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