Mass insert from array in mongodb JavaScript console

I am trying to do a massive insertion from the MongoDB console of an array into a collection.

I would 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 into the collection, it saves a single list with two objects.

db.test.find ()

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

This functionality appears on other drivers (for example, pymongo ), but I can not find a way to do this from the mongodb console, in the JavaScript code.

+4
source share
6 answers

To do this briefly: at the mongo console level there is no such API to insert.

-3
source

The function of inserting several documents into the collection has been added to the Mongo command shell version 2.1+. Now you can insert and massage documents into your collection.

Example:

db.users.insert([{name:'Jon', email:' Jon_Doe@mail.com '},{name:'Jane', email:' Jane_Doe@mail.com '}]) 

See this closed jira function request for more information:

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

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

+12
source

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

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

The array is available in 2.6.6.

 var bulk=db.posts.initializeUnorderedBulkOp() ; bulk.insert(obj1) ; bulk.insert(obj2);... bulk.execute() ; 
+1
source

You cannot bulk paste through an interactive command shell. But there is a command line tool that comes with Mongo that allows you to import multiple entries as 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 entries when using the json array file. Another important note is to make sure you have a file ending with a new line character. Otherwise, the last line will not be parsed.

0
source

Source: https://habr.com/ru/post/1342157/


All Articles