Mongodb – How to insert a document from a bash script to mongodb

bashinsertmongodb

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.

Best Answer

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);'