How can I insert a document from a bash script to mongodb?
18,817
Solution 1
You can inject javascript code from a javascript file:
mongo 127.0.0.1/MyDatabase script.js
with 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);'
Solution 2
insert some JSON into Mongo DB sample_db
, collection products_coll
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}
![Maximilian](https://i.stack.imgur.com/G3XRh.jpg?s=256&g=1)
Author by
Maximilian
I am currently finishing my studies at the TU München.
Updated on July 15, 2022Comments
-
Maximilian almost 2 years
What is the exact code I need to execute, to insert a document into a mongodb using bash. At the moment I am able to look documents in mongodb via bash script up, but inserting does not work.
-
Kip over 4 yearsjust FYI to anyone finding this: if you try to use
console.log()
inscript.js
you'll get an error that it's not defined. the equivalent isprint()
for mongo scripts. andprintjson()
is helpful too -
Eduardo Montoya almost 4 yearsIn my opinion, this answer is closer to the best solution. It uses stdin and pipe which makes it usable in a kind of a functional way.