0

I'm using MongoDB in node.js. I'm trying to update or insert many documents based on different conditions; however, MongoDB update (with upsert) only works with a single document or many documents with the same condition. Currently, I have an array containing the objects that I want to insert (Or update if the unique index exists) and I'm looping through the array and calling the updateOnce; however, I believe this method is not very efficient for a large number of objects that I'm going to have. What is a better way to achieve this?

var mongoUtil = require( './database.js' ); var db = mongoUtil.getDb(); //array of objects to insert: //NOTE: First + Last name is a unique index var users = [ {firstName:"John", lastName:"Doe", points:300}, {firstName:"Mickey", lastName:"Mouse", points:200} ]; var collection = db.collection( 'points' ); for(var i = 0; i < users.length; i++) { //If firstName and lastName already exists, update points. Otherwise insert new object collection.updateOne( {firstName: users[i].firstName, lastName: users[i].lastName}, {$set: {points: users[i].points}}, {upsert: true}, function(err,docs) { if(err) console.log(err); } ) } 
1

1 Answer 1

4

I solved this issue using .bulkWrite():

var mongoUtil = require( './database.js' ); var db = mongoUtil.getDb(); var collection = db.collection( 'points' ); var users = [ {firstName:"John", lastName:"Doe", points:300}, {firstName:"Mickey", lastName:"Mouse", points:200} ]; let userUpdate = users.map(user => ({ updateOne: { filter: {firstName: user.firstName, lastName: user.lastName}, update: {$set: user}, upsert: true } })); collection.bulkWrite(userUpdate).catch(e => { console.log(e); }); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.