简体   繁体   中英

MongoDB How to update multiple documents based on array of objects

Given array of objects :

const array = [{_id: 1, name: 'one'}, {_id: 2, name: 'two'}]

How do you construct a query so that it will update name field for each document in DB where document's id equals _id in array object?

This must be done in a single query. Query must use mongoDB node driver syntax.

for example:

// in DB : [{_id: 1, name: null, _id: 2, name: null }]
db.collection('sprints').update(....).then(...)
// after operation:
// in DB: [{_id: 1, name: "one", _id: 2, name: "two" }]

have you tried a construct like this:

Promise.all(array.map(entry =>
    db.collection('sprints').findOneAndUpdate({ _id: entry._id }, { name: entry.name }).save()
)).then(...);

its not the direct way but worked for me (in a test case)

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