I need to insert a big array of objects (about 1.5-2 millions) in mongodb from nodejs. How can i improve my inserting?
This is my code:
var sizeOfArray = arrayOfObjects.length; //sizeOfArray about 1.5-2 millions
for(var i = 0; i < sizeOfResult; ++i) {
newKey = {
field_1: result[i][1],
field_2: result[i][2],
field_3: result[i][3]
};
collection.insert(newKey, function(err, data) {
if (err) {
log.error('Error insert: ' + err);
}
});
}
To perform an update on all embedded array elements of each document that matches your query, use the filtered positional operator $[<identifier>] . The filtered positional operator $[<identifier>] specifies the matching array elements in the update document.
Insert MongoDB documents to a collection Alternatively, use the shortcut Ctrl + D (⌘ + D). This will open the Insert Document > JSON window. Type the fields to be added in JSON format. There is no need to add an _id field, as mongod will create this and assign the document a unique ObjectId value.
If the value is an array, $push appends the whole array as a single element. To add each element of the value separately, use the $each modifier with $push . For an example, see Append a Value to Arrays in Multiple Documents.
You can use bulk inserts.
There are two types of bulk operations:
- Ordered bulk operations. These operations execute all the operation in order and error out on the first write error.
- Unordered bulk operations. These operations execute all the operations in parallel and aggregates up all the errors. Unordered bulk operations do not guarantee order of execution.
So you can do something like this:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://myserver:27017/test", function(err, db) {
// Get the collection
var col = db.collection('myColl');
// Initialize the Ordered Batch
// You can use initializeUnorderedBulkOp to initialize Unordered Batch
var batch = col.initializeOrderedBulkOp();
for (var i = 0; i < sizeOfResult; ++i) {
var newKey = {
field_1: result[i][1],
field_2: result[i][2],
field_3: result[i][3]
};
batch.insert(newKey);
}
// Execute the operations
batch.execute(function(err, result) {
console.dir(err);
console.dir(result);
db.close();
});
});
As For Version > 3.2, insertMany has been introduced which uses bulkWrite under the hood for bulk insert purposes only.
insertMany supports ordered and unordered inserts. Unordered being faster as mongo decides the ordering. Likewise your implementation for best through-put should be ::
var sizeOfArray = arrayOfObjects.length;
for(var i = 0; i < sizeOfResult; ++i) {
newKey = {
field_1: result[i][1],
field_2: result[i][2],
field_3: result[i][3]
};
}
collection.insertMany(newKey, { ordered: false }).then((res) => {
console.log("Number of records inserted: " + res.insertedCount);
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With