How can I insert a document from a bash script to mongodb?

If you don't want to serve script from a file (I try not to source external files as much as possible) or not use --eval option which can be difficult to read if you have many entries, you can use a bash heredoc

You can type in 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 keep it in a script, just remove > which is actually prompt for a multiline command.

For in-script use, it should be as below:

#!/usr/bin/env bash

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

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