To find the user by name in MongoDB, use find(). Let us create a collection with documents −
> db.demo504.insertOne({"Name":"Chris"});{
"acknowledged" : true,
"insertedId" : ObjectId("5e8823ee987b6e0e9d18f570")
}
> db.demo504.insertOne({"Name":"John"});{
"acknowledged" : true,
"insertedId" : ObjectId("5e8823f2987b6e0e9d18f571")
}
> db.demo504.insertOne({"Name":"David"});{
"acknowledged" : true,
"insertedId" : ObjectId("5e8823f5987b6e0e9d18f572")
}Display all documents from a collection with the help of find() method −
> db.demo504.find();
This will produce the following output −
{ "_id" : ObjectId("5e8823ee987b6e0e9d18f570"), "Name" : "Chris" }
{ "_id" : ObjectId("5e8823f2987b6e0e9d18f571"), "Name" : "John" }
{ "_id" : ObjectId("5e8823f5987b6e0e9d18f572"), "Name" : "David" }Following is the query to find a user by name −
> db.demo504.find({Name:"John"});This will produce the following output −
{ "_id" : ObjectId("5e8823f2987b6e0e9d18f571"), "Name" : "John" }