DEV Community

loading...
Cover image for Advance Mongodb queries - cheatsheet

Advance Mongodb queries - cheatsheet

mrkanthaliya profile image Kanthaliya Updated on ・1 min read

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

Discussion

pic
Editor guide