I am using the current mongosh tool to run Mongo queries which may return very large result sets, which might not fit within the buffer of the command prompt (and even if they did, copying such results by hand would be time consuming and error prone). Therefore, I would like to have the ability to:
mongosh to a text file, andHere is the command I am currently running (details masked):
mongosh "mongodb://10.20.30.40:26017" --username my_username --password my_password
--authenticationDatabase my_database > output.txt
This is the current output I see in output.txt:
Current sessionID: 1ee96e0f6025ec328ea25ccc
Connecting to: mongodb://10.20.30.40:26017
Using MongoDB: 3.4.13
Using Mongosh Beta: 0.0.6
For more information about mongosh, please see our docs: https://docs.mongodb.com/mongodb-shell/
[1G[0J> [3G
So it seems that redirection to the output file is working. However, I can't seem to figure out how to specify a Mongo script with an actual query to the command line tool. For example, if I wanted to specify the following simple count query, how would I do it?
db.getCollection('my_collection').count();
Ideally, I would like output.txt to just have a single line with the count from this collection.
The earlier mongo command line tool seemed to have a number of ways of piping in a query, e.g. by specifying a script or using the --eval option. The documentation for mongosh claims that this tool is in Beta mode and supports some subset of mongo functionality. Does it support the ability to pass a query?
Meanwhile this also works with new mongosh, ensure you downloaded the latest version (1.1.9 or newer)
echo "db.getCollection('my_collection').countDocuments({});" | mongosh --norc --quiet > output.txt
mongosh --norc --quiet > output.txt <<EOF
db.getCollection('my_collection').countDocuments({});
EOF
mongosh --norc --quiet --eval "db.getCollection('my_collection').countDocuments({})" > output.txt
Note, with classic mongo shell you get this warning:
================
Warning: the "mongo" shell has been superseded by "mongosh",
which delivers improved usability and compatibility.The "mongo" shell has been deprecated and will be removed in
an upcoming release.
We recommend you begin using "mongosh".
For installation instructions, see
https://docs.mongodb.com/mongodb-shell/install/
================
which is not true in my opinion, I don't see new mongosh as successor for mongosh, yet. But I have to admit, it is getting better and better.
The only way to get rid of this warning is the --eval option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With