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("x开发者_如何学运维xxx"), "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.
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:'Jon_Doe@mail.com'},{name:'Jane', email:'Jane_Doe@mail.com'}])
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
objs.forEach(function(obj) { db.test.insert(obj) });
Bulk is available in 2.6.6.
var bulk=db.posts.initializeUnorderedBulkOp() ;
bulk.insert(obj1) ; bulk.insert(obj2);...
bulk.execute() ;
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.
To make it short: there is no such bulk insertion API available on the mongo console level.
精彩评论