Useful Commands for MongoDB

From Luis Gallego Hurtado - Not Another IT guy
Jump to: navigation, search

Querying MongoDB

Basic examples of MongoDB queries:

  • Filtering by equality:
db.getCollection('clients').find({"": "LUIS", "": "GALLEGO"})
  • Selecting the fields to return:
db.getCollection('clients').find({}, {personalData: 1, _id: 0 });
  • Sorting results:
db.getCollection('clients').find({}).sort({createdAt: -1})

Useful Commands for MongoDB

  • Connect to MongoDB cluster and open a shell
mongo --shell "mongodb+srv://<DATABASE_NAME>" --username <DATABASE_USER>
Example with some connection parameters:
mongo --shell "mongodb+srv://<DATABASE_NAME>?authSource=<DATABASE_NAME_WITH_USER_CREDENTIALS_COLLECTION>&retryWrites=true&w=majority" --username <DATABASE_USER>
  • Export a collection
mongoexport "mongodb+srv://<DATABASE_NAME>" --username <DATABASE_USER> --collection=<COLLECTION_NAME> --out=<EXPORT_FILE_NAME> --pretty