Search code examples
databasemongodbmongoose

MongoDB upsert with updateMany and an array in the filter


The code:

await this.tagModel.updateMany(
  { name: { $in: tagsArray } },
  { $inc: { count: 1 } },
  { upsert: true },
);

But it will upsert the item without a name value. I want to increment those tagcounts that are in the tagsArray (which works fine)

And if I can't find it then I want to upsert it with the name value that couldn't be found.

The alternative would be a for loop through the tagsArray and updateOne with an upsert, but that would mean multiple db calls instead of one


Solution

  • That is exactly what Model.bulkWrite is for.

    let ops = tagsArray.map( (tag) => { updateOne: {
               filter = {name: tag},
               update = {$inc: {count: 1}},
               upsert = true
    }})
    tagModel.bulkWrite(ops)