MongoDB – Top 10 Most Common Commands for Beginners

0
This article represents top 10 most commonly used commands for MongoDB beginners. Please feel free to comment/suggest if I missed to mention one or more important points. Also, sorry for the typos.

Following is the list of these commands:

Following is the list of these commands:

  1. Login into MongoDB: Following command can be used to login into MongoDB database for a particular database. Make sure that the user with credentials such as username and password exists in the database mentioned in place of dbname.
    	mongo -u <username> -p <password> --authenticationDatabase <dbname>
    	
  2. Show all databases: Once logged in as a user with appropriate role as userAdmin or userAdminAnyDatabase, one can see all the databases using command such as show dbs.
  3. Select Database to work with: In order to start working with a particular database, the command such as use databaseName can be executed.
  4. Authenticate and Logout from Database: When switching to different database using use dbName command, one would require to authenticate using a valid database user for that database. Following command can be used for authentication:
    	//
    	// Authenticate
    	//
    	db.auth("username", "password");
    	//
    	// Logout
    	//
    	db.logout()
    	
  5. List Down Collections, Users, Roles etc.: Following commands can be used to check existing collections, users etc.
    	//
    	// List down collections of the current database
    	//
    	show collections;
    	db.getCollectionNames();
    	//
    	// List down all the users of current database
    	//
    	show users;
    	db.getUsers();
    	//
    	// List down all the roles
    	//
    	show roles
    	
  6. Create a collection: Following command can be used to create a collection. The details on this command can be found on this page, Create Collection in a MongoDB database
    	db.createCollection("collectionName");
    	
  7. Insert a Document in a Collection: Once a collection is created, next step is to insert one or more documents. Following is a sample command for inserting a document in a collection.
    	//
    	// Insert single document
    	//
    	db.<collectionName>.insert({field1: "value", field2: "value"})
    	//
    	// Insert multiple documents
    	//
    	db.<collectionName>.insert([{field1: "value1"}, {field1: "value2"}])
    	db.<collectionName>.insertMany([{field1: "value1"}, {field1: "value2"}])
    	
  8. Save or Update Document: Following command, save, can be used to either update an existing document or insert a new one depending upon the document parameter passed to it. In case, the “_id” is passed matching an existing document, the document is updated. Otherwise, a new document is created. Internally, save method uses either insert or update command
    	//
    	// Matching document will be updated; In case, no document matching the ID is found, a new document is created
    	//
    	db.<collectionName>.save({"_id": new ObjectId("jhgsdjhgdsf"), field1: "value", field2: "value"}); 
    	
  9. Display Collection Records: Following commands can be used to retrieve collection records:
    	//
    	// Retrieve all records
    	//
    	db.<collectionName>.find();
    	//
    	// Retrieve limited number of records; Following command will print 10 results;
    	//
    	db.<collectionName>.find().limit(10);
    	//
    	// Retrieve records by id
    	//
    	db.<collectionName>.find({"_id": ObjectId("someid")});
    	//
    	// Retrieve values of specific collection attributes by passing an object having 
    	// attribute names assigned to 1 or 0 based on whether that attribute value needs 
    	// to be included in the output or not, respectively.
    	//
    	db.<collectionName>.find({"_id": ObjectId("someid")}, {field1: 1, field2: 1});
    	db.<collectionName>.find({"_id": ObjectId("someid")}, {field1: 0}); // Exclude field1
    	//
    	// Collection count
    	//
    	db.<collectionName>.count();
    	
  10. Administrative Commands: Following are some of the administrative commands which can be helpful in finding collection details such as storage size, total size, overall statistics.
    	//
    	// Get the collection statistics 
    	//
    	db.<collectionName>.stats()
    	db.printCollectionStats()
    	//
    	// Latency statistics for read, writes operations including average time taken for reads, writes
    	// and related umber of operations performed
    	//
    	db.<collectionName>.latencyStats()
    	//
    	// Get collection size for data and indexes
    	//
    	db.<collectionName>.dataSize() // Size of the collection
    	db.<collectionName>.storageSize() // Total size of document stored in the collection
    	db.<collectionName>.totalSize() // Total size in bytes for both collection data and indexes
    	db.<collectionName>.totalIndexSize() // Total size of all indexes in the collection
    	

     

Ajitesh Kumar

Ajitesh Kumar

Ajitesh is passionate about various different technologies including programming languages such as Java/JEE, Javascript, PHP, .NET, C/C++, mobile programming languages etc and, computing fundamentals such as application security, cloud computing, API, mobile apps, google glass, big data etc.Recently, he has been digging deep into the field of data science and machine learning.

Follow him on Twitter and Google+.
Ajitesh Kumar

Leave A Reply

Time limit is exhausted. Please reload the CAPTCHA.