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({"personalData.name.firstName": "LUIS", "personalData.name.firstLastName": "GALLEGO"})
  • Selecting the fields to return:
db.getCollection('clients').find({}, {personalData: 1, _id: 0 });

Updating MongoDB

  • Populating a property with value from another property:
db.getCollection('Video').find({}).forEach(function( aRow ) {
  db.getCollection('Video').update(
    { _id: aRow._id }, 
    { "$set": { "updatedAt": aRow.createdAt } });
});
  • 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://xxxxx.mongodb.net/<DATABASE_NAME>" --username <DATABASE_USER>
Example with some connection parameters:
mongo --shell "mongodb+srv://xxxxx.mongodb.net/<DATABASE_NAME>?authSource=<DATABASE_NAME_WITH_USER_CREDENTIALS_COLLECTION>&retryWrites=true&w=majority" --username <DATABASE_USER>
  • Export a collection
mongoexport "mongodb+srv://xxxxx.mongodb.net/<DATABASE_NAME>" --username <DATABASE_USER> --collection=<COLLECTION_NAME> --out=<EXPORT_FILE_NAME> --pretty