Inserting array of documents to Mongo collection

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                  }];

db.MyCollection.insert(array)

How I want it

Inserting an array with a pre-specified _id for each document should work properly. See the _id Field section of the Mongo docs. For example:

mongo> db.products.insert([
  { _id: '1', name: 'Product 1' }, 
  { _id: '2', name: 'Product 2' }
]);

will give:

mongo> db.products.find()
{ "_id" : "2", "name" : "Product 2" }
{ "_id" : "1", "name" : "Product 1" }

Hi @hwillson! It actually works like charm, but my problems is that whenever I am trying to add multiple documents into MongoDB collection, square brackets around the objects are understood as nested documents by Mongo. I am looking how I could insert objects from my array in collection at “root-level”.

What I am getting

What I want

Do it the other way around:

for(var i=0; i<array.length;i++) {
   Collection.insert(array[i]);
}

insert only inserts one document.

2 Likes

or using a functional approach:

array.forEach(doc => {
  Collection.insert(doc);
});
1 Like

Thx @rhywden and @robfallows you gents are gold. I cannot wait until I can work with JavaScript like a pro. I love the way that playing with JavaScript and back-end processing inserts, updates and removes enables to make the whole application act like “live” without having aggregation modules in use.

1 Like

You’re very welcome :slight_smile:

You could also do a bulk operation

const coll = Collection.rawCollection();
const bulk = coll.initializeUnorderedBulkOp();

items.forEach(item => bulk.insert(item));

bulk.execute();
2 Likes