Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Can't find user by name with MongoDB?
To find a user by name in MongoDB, use the find() method with a query document that specifies the name field and its value. This performs an exact match search on the specified field.
Syntax
db.collection.find({"fieldName": "value"});
Create Sample Data
Let us create a collection with user documents ?
db.demo504.insertMany([
{"Name": "Chris"},
{"Name": "John"},
{"Name": "David"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e8823ee987b6e0e9d18f570"),
ObjectId("5e8823f2987b6e0e9d18f571"),
ObjectId("5e8823f5987b6e0e9d18f572")
]
}
Display All Documents
db.demo504.find();
{ "_id": ObjectId("5e8823ee987b6e0e9d18f570"), "Name": "Chris" }
{ "_id": ObjectId("5e8823f2987b6e0e9d18f571"), "Name": "John" }
{ "_id": ObjectId("5e8823f5987b6e0e9d18f572"), "Name": "David" }
Find User by Name
Following is the query to find a user by name ?
db.demo504.find({"Name": "John"});
{ "_id": ObjectId("5e8823f2987b6e0e9d18f571"), "Name": "John" }
Case-Insensitive Search
For case-insensitive name searches, use regular expressions ?
db.demo504.find({"Name": /^john$/i});
{ "_id": ObjectId("5e8823f2987b6e0e9d18f571"), "Name": "John" }
Conclusion
Use find({"Name": "value"}) for exact name matches in MongoDB. For case-insensitive searches, employ regular expressions with the i flag to match names regardless of capitalization.
Advertisements
