DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Integration Dotenv With NestJS and Type ORM
  • A Developer's Guide to Database Sharding With MongoDB
  • Recovering an MS SQL Database From Suspect Mode: Step-By-Step Guide
  • Instant Integrations With API and Logic Automation

Trending

  • A Modern Stack for Building Scalable Systems
  • Beyond Linguistics: Real-Time Domain Event Mapping with WebSocket and Spring Boot
  • Streamlining Event Data in Event-Driven Ansible
  • Building Enterprise-Ready Landing Zones: Beyond the Initial Setup
  1. DZone
  2. Data Engineering
  3. Databases
  4. 10 Most Common Commands for MongoDB Beginners

10 Most Common Commands for MongoDB Beginners

These commands will be of great help to any database developer who missed the boat and is just getting started with MongoDB.

By 
Ajitesh Kumar user avatar
Ajitesh Kumar
·
Aug. 10, 17 · Opinion
Likes (4)
Comment
Save
Tweet
Share
318.6K Views

Join the DZone community and get the full member experience.

Join For Free

This article lists the top ten most commonly used commands for MongoDB beginners. Please feel free to comment and make suggestions if I failed to mention any important points! 

1. Log Into MongoDB

The following command can be used to log into the MongoDB database. Make sure that the user with credentials such as username and password exist 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 the appropriate role as userAdmin or userAdminAnyDatabase, the user can see all the databases using a command such as:

show dbs

3. Select Database to Work With

To start working with a particular database, the following command can be executed:

use databaseName

4. Authenticate and Log Out From Database

When switching to a different database using the use dbName command, the user is required to authenticate using a valid database user for that database. The following command can be used for authentication:

//
// Authenticate
//
db.auth("username", "password");
//
// Logout
//
db.logout()

5. List Down Collections, Users, Roles, etc.

The 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

The following command can be used to create a collection. The details on this command can be found on this page.

db.createCollection("collectionName"); 

7. Insert a Document in a Collection

Once a collection is created, the 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

The save command can be used to either update an existing document or insert a new one depending on the document parameter passed to it. If the _id passed matches an existing document, the document is updated. Otherwise, a new document is created. Internally, thesave method uses either the insert or the 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

The 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 that can be helpful in finding collection details such as storage size, total size, and 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

And that's it! These commands will be of great help to all those just getting started with MongoDB.

Command (computing) MongoDB Database code style

Published at DZone with permission of Ajitesh Kumar, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Integration Dotenv With NestJS and Type ORM
  • A Developer's Guide to Database Sharding With MongoDB
  • Recovering an MS SQL Database From Suspect Mode: Step-By-Step Guide
  • Instant Integrations With API and Logic Automation

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!