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
MongoDB query to find a specific city record from a collection
To find a specific city record from a MongoDB collection, use the find() method with a query document that matches the desired city name. This allows you to retrieve documents based on specific field values.
Syntax
db.collection.find({"fieldName": "value"});
Sample Data
Let us create a collection with city documents ?
db.demo30.insertMany([
{"City": "New York"},
{"City": "Los Angeles"},
{"City": "Chicago"},
{"City": "Los Angeles"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e174ceccfb11e5c34d898bd"),
ObjectId("5e174d0ecfb11e5c34d898be"),
ObjectId("5e174d18cfb11e5c34d898bf"),
ObjectId("5e174d1dcfb11e5c34d898c0")
]
}
Display all documents from the collection ?
db.demo30.find();
{ "_id": ObjectId("5e174ceccfb11e5c34d898bd"), "City": "New York" }
{ "_id": ObjectId("5e174d0ecfb11e5c34d898be"), "City": "Los Angeles" }
{ "_id": ObjectId("5e174d18cfb11e5c34d898bf"), "City": "Chicago" }
{ "_id": ObjectId("5e174d1dcfb11e5c34d898c0"), "City": "Los Angeles" }
Example: Find Specific City
Query to find all records for "Chicago" ?
db.demo30.find({"City": "Chicago"});
{ "_id": ObjectId("5e174d18cfb11e5c34d898bf"), "City": "Chicago" }
Find Multiple Matching Records
Query to find all "Los Angeles" records ?
db.demo30.find({"City": "Los Angeles"});
{ "_id": ObjectId("5e174d0ecfb11e5c34d898be"), "City": "Los Angeles" }
{ "_id": ObjectId("5e174d1dcfb11e5c34d898c0"), "City": "Los Angeles" }
Conclusion
Use find() with a query document to locate specific city records. MongoDB returns all documents that match the specified criteria, making it easy to filter collections by field values.
Advertisements
