How to connect to my MongoDB table by command line?

To connect to a MongoDB collection (table) using the command line, you need to first connect to the database and then use the db command with the collection name.

Syntax

db.collectionName.find();

Step 1: Connect to Database

First, switch to your target database and verify the current database ?

use sample;
db;
switched to db sample
sample

Step 2: List Available Collections

Check all collections in the current database ?

show collections;
arraySizeErrorDemo
basicInformationDemo
copyThisCollectionToSampleDatabaseDemo
deleteAllRecordsDemo
deleteDocuments
deleteDocumentsDemo
deleteSomeInformation
documentWithAParticularFieldValueDemo
employee
findListOfIdsDemo
findSubstring
getAllRecordsFromSourceCollectionDemo
getElementWithMaxIdDemo
internalArraySizeDemo
largestDocumentDemo
makingStudentInformationClone
oppositeAddToSetDemo
prettyDemo
returnOnlyUniqueValuesDemo
selectWhereInDemo
sourceCollection
studentInformation
sumOfValueDemo
sumTwoFieldsDemo
truncateDemo
updateInformation
userInformation

Step 3: Connect to Collection

Use the db command followed by the collection name to access your "table" ?

db.userInformation.find();
{ "_id" : ObjectId("5c6a765964f3d70fcc9147f5"), "Name" : "John", "Age" : 30, "isStudent" : false, "Subjects" : [ "Introduction to java", "Introduction to MongoDB" ] }

Key Points

  • MongoDB uses collections instead of tables (SQL terminology).
  • Always switch to the correct database using use databaseName first.
  • The find() method retrieves all documents from the collection.

Conclusion

Connecting to a MongoDB collection requires switching to the database first, then using db.collectionName.find() to access and query the data. Remember that MongoDB uses collections, not tables.

Updated on: 2026-03-15T00:35:12+05:30

242 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements