Count the documents with a field value beginning with 13

To count documents where a field value begins with "13", use MongoDB's $regex operator with the ^ anchor for pattern matching, combined with the count() method for efficient counting.

Syntax

db.collection.count({
    "fieldName": { "$regex": "^13" }
});

Sample Data

db.demo570.insertMany([
    {Information: {Value: "13675"}},
    {Information: {Value: "14135"}},
    {Information: {Value: "15113"}},
    {Information: {Value: "13141"}}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e90959b39cfeaaf0b97b583"),
        ObjectId("5e9095a739cfeaaf0b97b584"),
        ObjectId("5e9095b639cfeaaf0b97b585"),
        ObjectId("5e9095c139cfeaaf0b97b586")
    ]
}

Display All Documents

db.demo570.find();
{ "_id": ObjectId("5e90959b39cfeaaf0b97b583"), "Information": { "Value": "13675" } }
{ "_id": ObjectId("5e9095a739cfeaaf0b97b584"), "Information": { "Value": "14135" } }
{ "_id": ObjectId("5e9095b639cfeaaf0b97b585"), "Information": { "Value": "15113" } }
{ "_id": ObjectId("5e9095c139cfeaaf0b97b586"), "Information": { "Value": "13141" } }

Count Documents Starting with "13"

db.demo570.count({
    "Information.Value": { "$regex": "^13" }
});
2

Key Points

  • The ^ symbol matches the beginning of the string
  • Use count() instead of find().count() for better performance
  • This query can utilize indexes on the field for faster execution

Conclusion

The $regex operator with ^13 pattern efficiently counts documents where field values start with "13". This approach supports index optimization and provides faster performance for counting operations.

Updated on: 2026-03-15T03:36:41+05:30

131 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements