Query MongoDB collection starting with _?

To work with MongoDB collections that have names starting with underscore (_), you need to use the getCollection() method instead of the standard dot notation, as collection names beginning with underscore require special handling.

Syntax

Create collection starting with underscore:

db.createCollection('_yourCollectionName');

Insert documents into underscore collection:

db.getCollection('_yourCollectionName').insertOne({
    "field1": "value1",
    "field2": "value2"
});

Query documents from underscore collection:

db.getCollection('_yourCollectionName').find();

Example

Let us create a collection starting with underscore and insert sample documents:

db.createCollection('_testUnderscoreCollectionDemo');
{ "ok" : 1 }

Insert multiple documents using insertMany():

db.getCollection('_testUnderscoreCollectionDemo').insertMany([
    {"StudentFirstName": "John", "StudentAge": 23},
    {"StudentFirstName": "Carol", "StudentAge": 21}
]);
{
    "acknowledged" : true,
    "insertedIds" : [
        ObjectId("5ccfb4a6140b992277dae0e4"),
        ObjectId("5ccfb4af140b992277dae0e5")
    ]
}

Query the Collection

Display all documents from the underscore collection:

db.getCollection('_testUnderscoreCollectionDemo').find().pretty();
{
    "_id" : ObjectId("5ccfb4a6140b992277dae0e4"),
    "StudentFirstName" : "John",
    "StudentAge" : 23
}
{
    "_id" : ObjectId("5ccfb4af140b992277dae0e5"),
    "StudentFirstName" : "Carol",
    "StudentAge" : 21
}

Key Points

  • Always use getCollection('_collectionName') for collections starting with underscore
  • Regular dot notation db._collectionName will not work properly
  • All standard MongoDB operations work the same way with getCollection()

Conclusion

MongoDB collections starting with underscore require the getCollection() method for proper access. This method ensures correct handling of special collection names while maintaining all standard MongoDB functionality.

Updated on: 2026-03-15T00:59:58+05:30

304 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements