javascript document - Insert array of objects into MongoDB

with data (5)

I wonder how I could insert array of objects to Mongo collection "root-level documents" with own pre-defined _id values.

I have tried db.MyCollection.insert(array); but it creates nested documents under one single generated _id in MongoDB.

var array = [

      { _id: 'rg8nsoqsxhpNYho2N',
        goals: 0,
        assists: 1,
        total: 1                  },

      { _id: 'yKMx6sHQboL5m8Lqx',
        goals: 0,
        assists: 1,
        total: 1                  }];


What I want


Go through this Link To get Exact Outcome the way you want:

You can use MongoDB Bulk to insert multiple document in one single call to the database.

First iterate over your array and call the bulk method for each item:


After the loop, call execute:


Take a look at the refereed documentation to learn more.

Why not iterate over the array objects, and insert them one at a time?

array.forEach((item) => db.MyCollection.insert(item));

db.collection.insertMany() is what you need (supported from 3.2):

     { name: "bob", age: 42, status: "A", },
     { name: "ahn", age: 22, status: "A", },
     { name: "xi", age: 34, status: "D", }


    "acknowledged" : true,
    "insertedIds" : [ 

There isn't any for each loop in native JavaScript. You can either use libraries to get this functionality (I recommend Underscore.js), use a simple for in loop.

for (var instance in objects) {

However, note that there may be reasons to use an even simpler for loop (see question Why is using “for…in” with array iteration such a bad idea?)

var instance;
for (var i=0; i < objects.length; i++) {
    var instance = objects[i];

javascript json mongodb