M
M
miniven2018-08-20 16:14:08
JavaScript
miniven, 2018-08-20 16:14:08

How to update multiple documents at once in mongodb?

Is it possible to update several documents at once, and with different values?
For example, I send a request:

{
  "5b7abaf46081420c3042867a": { "lastChosen": false },
  "5b7abafe6081420c3042867c": { "lastChosen": true }
}

And I need the documents with these id to be updated according to the objects specified for them. How is it possible to do this? I tried it in a loop, but I don’t understand how it will be correct to return the answer when all queries to the database are over.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
lega, 2018-08-20
@miniven

1 way, send asynchronously all requests with the key w=0 (loop) except the last one, which is sent with the key w=1 - in 99% it will be processed last and return the completion status
2 use bulkwrite

A
Abcdefgk, 2018-08-20
@Abcdefgk

In fact, before the advent of the clever async library, they simply created a var count = 0 variable and plus it at the end of each callback of accessing the database, after which - in each callback - there was a condition (assume that there are five accesses) "if count == 5, then res.end(...)"
The response was sent - when all asynchronous work was completed.
(for this explanation of the ancient mechanism of "fighting asynchrony" I was once forever banned in Russian Stackoverflow)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question