How can I enlarge multiple objects using MongoDB & Node.js?

Let's say I have a number of movie genres:

[ 
    { id: 28, name: 'Action' },
    { id: 12, name: 'Adventure' },
    { id: 16, name: 'Animation' },
    { id: 35, name: 'Comedy' },
    { id: 80, name: 'Crime' },
    { id: 99, name: 'Documentary' },
    { id: 18, name: 'Drama' },
    { id: 10751, name: 'Family' },
    { id: 14, name: 'Fantasy' },
    { id: 10769, name: 'Foreign' },
    { id: 36, name: 'History' },
    { id: 27, name: 'Horror' },
    { id: 10402, name: 'Music' },
    { id: 9648, name: 'Mystery' },
    { id: 10749, name: 'Romance' },
    { id: 878, name: 'Science Fiction' },
    { id: 10770, name: 'TV Movie' },
    { id: 53, name: 'Thriller' },
    { id: 10752, name: 'War' },
    { id: 37, name: 'Western' }
]

and I have a connection to an instance of MongoDB (v3.2): dband I am using the standard mongodb driver Node.js ( const mongodb = require('mongodb').MongoClient).

What I want to do is one operation of increasing the volume in the collection, for example genres, where the field is _iddisplayed in the field of idour genre objects.

Now I know that I could iterate over each element in the array and do a simple upsert:

for (let i = 0; i < genres.length; i++) {
  await db.collection('genres').update(
    { _id: genres[i].id },
    genres[i],
    { upsert: true }
  );
}

But it seems wasteful and wrong.

Is there an easier way to do what should be a relatively simple task?

thank

+4
source share
2

API bulkWrite :

var bulkUpdateOps = genres.map(function(doc) {
    return {
        "updateOne": {
            "filter": { "_id": doc.id },
            "update": { "$set": { "name": doc.name } },
            "upsert": true
        }
    };
});

db.collection('genres').bulkWrite(bulkUpdateOps, function(err, r) {
    // do something with result
}

, > 1000, , 500, , 500 :

var bulkUpdateOps = [],
    counter = 0;

genres.forEach(function(doc) {
    bulkUpdateOps.push({
        "updateOne": {
            "filter": { "_id": doc.id },
            "update": { "$set": { "name": doc.name } },
            "upsert": true
        }
    });
    counter++;

    if (counter % 500 == 0) {
        db.collection('genres').bulkWrite(bulkUpdateOps, function(err, r) {
            // do something with result
        });
        bulkUpdateOps = [];
    }
})

if (counter % 500 != 0) {
    db.collection('genres').bulkWrite(bulkUpdateOps, function(err, r) {
        // do something with result
    }
}
+5

:

db.collection('genres').update(genres, {upsert: true, multi: true});

: ...

UPDATE: id _id:

var _genres = genres.map(function(genre) {
   return { _id: genre.id, name: genre.name };
});

db.collection('genres').update(_genres, {upsert: true, multi: true});
+2

All Articles