[英]How can I update some documents with different data in mongodb
If I have the ids for the following documents that belongs to a big collection and a newBusinessId to update those documents. 如果我具有属于一个大集合的以下文档的ID,并具有一个newBusinessId来更新这些文档。 Something like this:
像这样:
const newBusinessId = '8abc4cef176aa342154d00c0'
const paymentsIds = ['5aba5cef176aa342154d2345', '5aba5cef176aa342154d6789']
And those ids belong to the following documents in my database: 这些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'
},
]
I want to update those documents with the same businessId : newBusinessId , with the state value of INIT and the fields ( comment, expense ) to be set with the values of ( startComment, startExpense ) so I can have the following result after updating: 我想使用相同的businessId : newBusinessId更新那些文档,并使用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'
},
]
Any idea how? 任何想法如何? I appreciate your toughts!
我感谢你的强硬!
in order to update a field with another field's value in the same object ( expense = startExpense for example ), you have to iterate through, try this : 为了用同一对象中另一个字段的值更新一个字段(例如,费用= 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.