Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bulk insert from Array in mongodb JavaScript console

I'm trying to make a bulk insert from the MongoDB console of an array into a collection.

I'd like to do something similar to this.

obj1 = {_id:ObjectId(),blabla:1};

obj2 = {_id:ObjectId(),blabla:2};

objs = [obj1, obj2];

db.test.insert(objs);

db.test.find()

> {"_id": ObjectId("xxxx"), "blabla": 1} > {"_id": ObjectId("xxxx"), "blabla": 2}

But, instead of inserting two objects on the collection, it stores one list with the two objects.

db.test.find()

> {"_id": ObjectId("xxx"), "0":{"_id": ObjectId("xxxx"), "blabla": 1}, "1":{"_id": ObjectId("xxxx"), "blabla": 2} }

That functionality appears to present on other drivers (like pymongo), but I can't find a way of doing that from the mongodb console, in JavaScript code.

like image 413
Khelben Avatar asked Mar 03 '11 17:03

Khelben


People also ask

What is batch insert in MongoDB?

Multiple documents can be inserted at a time in MongoDB using bulk insert operation where an array of documents is passed to the insert method as parameter.

How do I insert multiple files in MongoDB Robo 3t?

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.


2 Answers

The feature to insert multiple documents into a collection has been added to Mongo command shell version 2.1+. Now You can insert and array of documents into your collection.

Example:

db.users.insert([{name:'Jon', email:'[email protected]'},{name:'Jane', email:'[email protected]'}])

For more information look at these jira closed feature request:

https://jira.mongodb.org/browse/SERVER-3819

https://jira.mongodb.org/browse/SERVER-2395

like image 87
Ida N Avatar answered Nov 02 '22 23:11

Ida N


There is an existing feature request for this. http://jira.mongodb.org/browse/SERVER-2429

like image 26
Sridhar Avatar answered Nov 02 '22 22:11

Sridhar