5

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.

5 Answers 5

13

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1
objs.forEach(function(obj) { db.test.insert(obj) });

Comments

1

Bulk is available in 2.6.6.

var bulk=db.posts.initializeUnorderedBulkOp() ;
bulk.insert(obj1) ; bulk.insert(obj2);...

bulk.execute() ;

Comments

0

You cannot do a bulk insert through the interactive command shell. But there is a commandline tool that ships with Mongo that allows you to import multiple records as either JSON (your best option), CSV or Binary.

> mongoimport -h <host> -d <database> -c <collection> -u <user> -p <password> --file <input file> --jsonArray

The jsonArray flag will allow you to insert multiple records when you use the json array file. Another important note is to make sure you have the file ending with a new line character. Otherwise the last line will not be parsed.

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.