DEV Community

Cover image for Advance Mongodb queries - cheatsheet
Kanthaliya
Kanthaliya

Posted on • Edited on

5 3

Advance Mongodb queries - cheatsheet

Here are few less used but important Mongodb queries I use now and then. Will keep updating this page If I get to use different less used queries.

Copy database

db.copyDatabase("dbname", "dbnamenew")
Enter fullscreen mode Exit fullscreen mode

Drop database

use dbname
db.dropDatabase()
Enter fullscreen mode Exit fullscreen mode

Active operations

db.currentOp() or db.adminCommand( { lockInfo: 1 } )
Enter fullscreen mode Exit fullscreen mode

Kill operation

db.killOp(opid)
Enter fullscreen mode Exit fullscreen mode

Query stats

db.collection.find({"status":"single"}).explain( "executionStats")
Enter fullscreen mode Exit fullscreen mode

DB stats (in GB)

db.stats(1024*1024*1024)
Enter fullscreen mode Exit fullscreen mode

Create index

db.collection.createIndex( { status: 1 } )
Enter fullscreen mode Exit fullscreen mode

Get indexes on collection

db.collection.getIndexes()
Enter fullscreen mode Exit fullscreen mode

Create read only access for user on mongodb

db.createUser({user: "example_read",pwd: "12345", roles: [{role:"read", db: "dbname"}]})
Enter fullscreen mode Exit fullscreen mode

Get user roles on mongodb

db.getUser("user_name")
Enter fullscreen mode Exit fullscreen mode

Export collection

mongoexport --host=10.0.0.1:27017 --username=example --authenticationDatabase=admin --collection=example_mapper --db=dbname --out=example_mapper.json
Enter fullscreen mode Exit fullscreen mode

Import from collection

mongoimport --host=10.0.0.1:27017 --username=example --authenticationDatabase=admin --collection=example_mapper --db=dbname --file=example_mapper.json
Enter fullscreen mode Exit fullscreen mode

Dump mongodb

mongodump --host=10.0.0.1:27017 --username=example --authenticationDatabase=admin --db db_example --out dumps/
Enter fullscreen mode Exit fullscreen mode

Restore mongodb from dump

mongorestore --host=10.0.0.1:27017 --username=example --authenticationDatabase=admin  dumps/
Enter fullscreen mode Exit fullscreen mode

Shell connect with ssh

mongo --ssl --host docdb.amazonaws.com:27017 --sslCAFile rds.pem --username example --password asddasdasd
Enter fullscreen mode Exit fullscreen mode

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay