Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert array of objects into MongoDB

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);

enter image description here

What I want

enter image description here

like image 972
justdiehard Avatar asked Apr 27 '16 11:04

justdiehard


1 Answers

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

db.users.insertMany(
   [
     { name: "bob", age: 42, status: "A", },
     { name: "ahn", age: 22, status: "A", },
     { name: "xi", age: 34, status: "D", }
   ]
)

output:

{
    "acknowledged" : true,
    "insertedIds" : [ 
        ObjectId("57d6c1d02e9af409e0553dff"), 
        ObjectId("57d6c1d02323d119e0b3c0e8"), 
        ObjectId("57d6c1d22323d119e0b3c16c")
    ]
}
like image 118
marmor Avatar answered Oct 08 '22 18:10

marmor