Count the documents with a field value beginning with 13

MongoDBDatabaseBig Data Analytics

To count the documents, use $count. For values beginning with 13, use $regex. You can use $regex. Let us create a collection with documents −

> db.demo570.insertOne({Information:{Value:"13675"}});{
   "acknowledged" : true, "insertedId" : ObjectId("5e90959b39cfeaaf0b97b583")
}
> db.demo570.insertOne({Information:{Value:"14135"}});{
   "acknowledged" : true, "insertedId" : ObjectId("5e9095a739cfeaaf0b97b584")
}
> db.demo570.insertOne({Information:{Value:"15113"}});{
   "acknowledged" : true, "insertedId" : ObjectId("5e9095b639cfeaaf0b97b585")
}
> db.demo570.insertOne({Information:{Value:"13141"}});{
   "acknowledged" : true, "insertedId" : ObjectId("5e9095c139cfeaaf0b97b586")
}

Display all documents from a collection with the help of find() method −

> db.demo570.find();

This will produce the following output −

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

Following is the query for faster performance that will use an index −

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

This will produce the following output −

2
raja
Published on 14-May-2020 08:38:12
Advertisements