Run MongoDB Shell the simple way:

mongo

Run MongoDB Shell with username and password:

mongo -u someUsername -p somePassword –authenticationDatabase someDb

The ‘someDb’ above is usually just ‘admin’.

Run MongoDB Shell with username, password on a replica set:

mongo -u someUsername -p somePassword –authenticationDatabase someDb –host replicaSetName/hostNameOrIp databaseName

Run MongoDB Shell with username, password on a replica set and execute a JavaScript file:

mongo -u someUsername -p somePassword –authenticationDatabase someDb –host replicaSetName/hostNameOrIp databaseName < someCodeFile.js

A simple MongoDB Shell script file in JavaScript (for more details, see: https://docs.mongodb.com/manual/tutorial/write-scripts-for-the-mongo-shell):

db.users.find({
  //any query here
}).
snapshot().forEach(function(Doc){
  print(Doc._id);
  var Obj_Id    = Doc._id;
  var Forename  = Doc.Forename;
  var Surname   = Doc.Surname;
  var Full_Name = Forename+" "+Surname;

  db.users.update({
    _id: Obj_Id
  },
  {$set:{
    Full_Name: Full_Name
  }}).
});

Other useful MongoDB Shell commands:

  • help
  • db.help()
  • db..help()
  • show dbs
  • use
  • show collections
  • load()
  • db.auth()
  • db..find(), insert(), update(), save(), remove(), drop(), createIndex()
  • db.getCollectionNames()

More MongoDB Shell reference: https://docs.mongodb.com/manual/reference/mongo-shell

Advertisements