简体   繁体   中英

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. Something like this:

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

And those ids belong to the following documents in my database:

[
  {
    _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:

[
  {
    _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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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