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 for a single field
To query a single field in MongoDB, use the find() method with projection. Projection allows you to specify which fields to include or exclude from the query results.
Syntax
db.collection.find({}, { "fieldName": 1, "_id": 0 });
Sample Data
Let us first create a collection with documents ?
db.demo10.insertMany([
{ "StudentId": 101, "StudentName": "Chris" },
{ "StudentId": 102, "StudentName": "David" },
{ "StudentId": 103, "StudentName": "Bob" }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e0f68a7d7df943a7cec4f9b"),
ObjectId("5e0f68afd7df943a7cec4f9c"),
ObjectId("5e0f68b5d7df943a7cec4f9d")
]
}
Display All Documents
Following is the query to display all documents from a collection ?
db.demo10.find();
{ "_id": ObjectId("5e0f68a7d7df943a7cec4f9b"), "StudentId": 101, "StudentName": "Chris" }
{ "_id": ObjectId("5e0f68afd7df943a7cec4f9c"), "StudentId": 102, "StudentName": "David" }
{ "_id": ObjectId("5e0f68b5d7df943a7cec4f9d"), "StudentId": 103, "StudentName": "Bob" }
Query Single Field
Here is the query to retrieve only the StudentName field ?
db.demo10.find({}, { "_id": 0, "StudentId": 0 });
{ "StudentName": "Chris" }
{ "StudentName": "David" }
{ "StudentName": "Bob" }
Alternative Method
You can also explicitly include only the required field ?
db.demo10.find({}, { "StudentName": 1, "_id": 0 });
{ "StudentName": "Chris" }
{ "StudentName": "David" }
{ "StudentName": "Bob" }
Conclusion
Use projection with find() to query specific fields. Set unwanted fields to 0 to exclude them, or set desired fields to 1 to include only those fields in the result.
Advertisements
