Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB updateMany, dynamic filter field

When using the .updateMany(filter, update, option). How can I set a dynamic filter field for every document?

I have an array of documents like this:

[
    {
        time: 1,
        data: []
    },
    {
        time: 2,
        data: []
    },
    {
        time: 3,
        data: []
    }
]

Each with a unique timestamp. In case the timestamp already exists, the corresponding document should be updated with the new data but if the time doesn't exists, create a new document.

https://docs.mongodb.com/manual/reference/method/db.collection.updateMany/

But as it seems, .updateMany() only allows a static filter field. Like this

Candles.updateMany({time: 'someStaticTime'}, documents);

while I would prefer something like this

Candles.updateMany({time: $currentInsertingDocument.time}, documents);

Is this possible without looping over each document seperate??

like image 727
DutchKevv Avatar asked Aug 31 '25 02:08

DutchKevv


1 Answers

You should use Mongo's Bulk API

like image 73
Michael Avatar answered Sep 04 '25 00:09

Michael