How to find MongoDB documents with a specific string?

MongoDBDatabaseBig Data Analytics

To find documents with a specific string, use find() and in that search for a string with regex. Let us create a collection with documents −

> db.demo409.insertOne({"Name":"John Doe"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e70e4e515dc524f7022767c")
}
> db.demo409.insertOne({"Name":"Chris Brown"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e70e4ec15dc524f7022767d")
}
> db.demo409.insertOne({"Name":"Robert Doe"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e70e4f415dc524f7022767e")
}
> db.demo409.insertOne({"Name":"David Brown"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e70e4fe15dc524f7022767f")
}

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

> db.demo409.find();

This will produce the following output −

{ "_id" : ObjectId("5e70e4e515dc524f7022767c"), "Name" : "John Doe" }
{ "_id" : ObjectId("5e70e4ec15dc524f7022767d"), "Name" : "Chris Brown" }
{ "_id" : ObjectId("5e70e4f415dc524f7022767e"), "Name" : "Robert Doe" }
{ "_id" : ObjectId("5e70e4fe15dc524f7022767f"), "Name" : "David Brown" }

Following is the query to find documents with a specific string in MongoDB −

> db.demo409.find({Name: /Doe/});

This will produce the following output −

{ "_id" : ObjectId("5e70e4e515dc524f7022767c"), "Name" : "John Doe" }
{ "_id" : ObjectId("5e70e4f415dc524f7022767e"), "Name" : "Robert Doe" }
raja
Published on 03-Apr-2020 16:44:55
Advertisements