21

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

8
  • 1
    db.MyCollection.insert(array) should work. Are you getting any error message? Commented Apr 27, 2016 at 11:05
  • Insert process works and I am having the data in collection but I would like to have objects at "root-level" and now they are inserted under "0": {}, "1": {} and so on. I would like to insert all my objects as "root-level" document with my _id value Commented Apr 27, 2016 at 11:09
  • With the document you show us you can't get that result. Commented Apr 27, 2016 at 11:16
  • 1
    @sportsdiehard as user3100115 said db.collectionName.insert(array) will work for you, try using mongo shell for insert Commented Apr 27, 2016 at 12:06
  • 1
    I see you have edited your question after I posted my answer. Have you tried it? Further, you should not post using screenshots, please, remove them an paste in the question body. Commented Apr 27, 2016 at 13:12

3 Answers 3

16

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")
    ]
}
Sign up to request clarification or add additional context in comments.

1 Comment

is there a way to "upsert" many similar to this? i want to push an array everytime but mostly the items will exist
4

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

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

1 Comment

I have done this, but its not letting me to add "result/succesful" function into insert
1

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:

bulk.insert(item)

After the loop, call execute:

bulk.execute()

Take a look at the refereed documentation to learn more.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.