Query MongoDB with length criteria?


To query MongoDB with length criteria, you can use regex. Following is the syntax

db.yourCollectionName.find({ ‘yourFieldName’: { $regex: /^.{yourLengthValue1,yourLengthValue2}$/ } });

Let us create a collection with documents. Following is the query

> db.queryLengthDemo.insertOne({"StudentFullName":"John Smith"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9a01ae353decbc2fc927c0")
}
> db.queryLengthDemo.insertOne({"StudentFullName":"John Doe"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9a01b4353decbc2fc927c1")
}
> db.queryLengthDemo.insertOne({"StudentFullName":"David Miller"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9a01c2353decbc2fc927c2")
}
> db.queryLengthDemo.insertOne({"StudentFullName":"Robert Taylor"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9a01e2353decbc2fc927c3")
}
> db.queryLengthDemo.insertOne({"StudentFullName":"Chris Williams"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9a01f1353decbc2fc927c4")
}

Following is the query to display all documents from a collection with the help of find() method

> db.queryLengthDemo.find().pretty();

This will produce the following output

{
   "_id" : ObjectId("5c9a01ae353decbc2fc927c0"),
   "StudentFullName" : "John Smith"
}
{
   "_id" : ObjectId("5c9a01b4353decbc2fc927c1"),
   "StudentFullName" : "John Doe"
}
{
   "_id" : ObjectId("5c9a01c2353decbc2fc927c2"),
   "StudentFullName" : "David Miller"
}
{
   "_id" : ObjectId("5c9a01e2353decbc2fc927c3"),
   "StudentFullName" : "Robert Taylor"
}
{
   "_id" : ObjectId("5c9a01f1353decbc2fc927c4"),
   "StudentFullName" : "Chris Williams"
}

Following is the query in MongoDB with length criteria

> db.queryLengthDemo.find({ StudentFullName: { $regex: /^.{9,12}$/ } }).pretty();

This will produce the following output

{
   "_id" : ObjectId("5c9a01ae353decbc2fc927c0"),
   "StudentFullName" : "John Smith"
}
{
   "_id" : ObjectId("5c9a01c2353decbc2fc927c2"),
   "StudentFullName" : "David Miller"
}

Updated on: 30-Jul-2019

119 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements