How to insert a document from bash script in mongodb?

What is the exact code I need to execute to insert a document in mongodb using bash. At the moment, I can view documents in mongodb through the bash script up, but the insert does not work.

+8
source share
3 answers

You can enter JavaScript code from a JavaScript file:

mongo 127.0.0.1/MyDatabase script.js 

using script.js:

 var document = { name : "document_name", title : "document_title" }; db.MyCollection.insert(document); 

or directly:

 mongo 127.0.0.1/MyDatabase --eval 'var document = { name : "document_name", title : "document_title" }; db.MyCollection.insert(document);' 
+18
source

If you do not want to serve the script from a file (I try not to distribute external files as much as possible) or not to use the --eval parameter, which can be hard to read if you have many entries, you can use bash heredoc

You can enter the terminal:

 -bash-4.1$ mongo mongodb://myServerAddress/myDbName <<EOF > db.myCollectionName.insert({ > name: "doc name", > title: "doc title" > }) > EOF 

Result:

 MongoDB shell version v3.4.1 connecting to: mongodb://myServerAddress/myDbName MongoDB server version: 3.0.7 WARNING: shell and server versions do not match WriteResult({ "nInserted" : 1 }) bye -bash-4.1$ 

If you want to save it in a script, just remove the > , which really requests a multiline command.

To use a script, it must be as follows:

 #!/usr/bin/env bash mongo mongodb://myServerAddress/myDbName <<EOF db.myCollectionName.insert({ name: "doc name", title: "doc title" }) EOF 
+2
source

insert a little JSON in Mongo DB sample_db , products_coll collection

 echo '{ item: "card", qty: 115 }' | \ sed ' s@ ^@db.products_coll.insert( @; s@ $@ ) @' | mongo sample_db MongoDB shell version v3.6.3 connecting to: mongodb://127.0.0.1:27017/sample_db MongoDB server version: 3.6.3 WriteResult({ "nInserted" : 1 }) bye 

make sure it is here

 mongoexport -d sample_db -c products_coll {"_id":{"$oid":"5d27e83152a049227799710e"},"item":"card","qty":115.0} 
0
source

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


All Articles