Using mongo cli utility can be handy way to query mongo db and automate few simple use cases. This article covers some handy commands which can be used with mongo cli utility. This article assumes that you have mongo server installed on local machine. I tested these commands on Mac. But these should work on any other OS.
Install mongo server
Use the following command on Mac:
$ brew install mongo // To run mongodb one time $ launchctl load /usr/local/opt/mongodb/homebrew.mxcl.mongodb.plist // To run on startup ln -sfv /usr/local/opt/mongodb/*.plist ~/Library/LaunchAgents
Create collection
Create collection in new or existing db:
$ printf "db.createCollection('testcollection1')" | mongo --quiet testdb1 { "ok" : 1 } $ printf "db.getCollectionNames()" | mongo --quiet testdb1 [ "system.indexes", "testcollection1" ] //or $ printf "show collections" | mongo --quiet testdb1 system.indexes testcollection1
drop collection or delete documents in a collection
To drop a collection:
$ printf 'db.testcollection1.drop()' | mongo --quiet testdb1 true
To delete documents in a collection:
$ printf "db.testcollection1.remove({})" | mongo --quiet testdb1 WriteResult({ "nRemoved" : 0 })
List dbs and collections
List dbs and collections in mongo
$ printf "show dbs" | mongo --quiet local 0.078GB testdb1 0.078GB $ printf "show collections" | mongo --quiet testdb1 system.indexes testcollection1
insert documents
Insert few test documents in collection
$ printf 'db.testcollection1.insert({key1:"value1"})' | mongo --quiet testdb1 WriteResult({ "nInserted" : 1 }) $ printf 'db.testcollection1.insert({})' | mongo --quiet testdb1 $ printf 'db.testcollection1.insert({})' | mongo --quiet testdb1 // With each document insert an the _id field is automatically created.
Query documents from a collection
Query all documents with limit 1000
$ printf 'db.testcollection1.find({}).limit(1000)' | mongo --quiet testdb1 { "_id" : ObjectId("55bf6d34e72610341df44d43"), "key1" : "value1" } { "_id" : ObjectId("55bf6d8f8d923f4cfbb3294f") } { "_id" : ObjectId("55bf6d926a78c27ae1e81d7a") }
You can skip limit(1000) to return all documents.
Query all values where key1 is not equal to “value1”
$ printf 'db.testcollection1.find({key1:{$ne:"value1"}})' | mongo --quiet testdb1