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.
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.
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.
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
There is an existing feature request for this. http://jira.mongodb.org/browse/SERVER-2429
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With