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
How to get the equivalent for SELECT column1, column2 FROM tbl in MongoDB Database?
In MongoDB, you can select specific fields (columns) from a collection using projection in the find() method. This is equivalent to the SQL SELECT column1, column2 FROM table statement.
Syntax
db.collectionName.find({}, {"field1": 1, "field2": 1})
Use 1 to include fields and 0 to exclude fields. The _id field is included by default unless explicitly excluded.
Sample Data
db.customers.insertMany([
{"CustomerName": "John", "CustomerAge": 26, "CustomerCountryName": "US"},
{"CustomerName": "David", "CustomerAge": 22, "CustomerCountryName": "AUS"},
{"CustomerName": "Chris", "CustomerAge": 24, "CustomerCountryName": "UK"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("..."),
ObjectId("..."),
ObjectId("...")
]
}
Example 1: Select Specific Fields (Include _id)
db.customers.find({}, {"CustomerName": 1, "CustomerAge": 1});
{
"_id": ObjectId("5c92c6205259fcd19549980a"),
"CustomerName": "John",
"CustomerAge": 26
}
{
"_id": ObjectId("5c92c6305259fcd19549980b"),
"CustomerName": "David",
"CustomerAge": 22
}
{
"_id": ObjectId("5c92c6415259fcd19549980c"),
"CustomerName": "Chris",
"CustomerAge": 24
}
Example 2: Select Fields Without _id
db.customers.find({}, {_id: 0, "CustomerName": 1, "CustomerAge": 1});
{"CustomerName": "John", "CustomerAge": 26}
{"CustomerName": "David", "CustomerAge": 22}
{"CustomerName": "Chris", "CustomerAge": 24}
Key Points
- Use
1to include specific fields in the result - Use
0to exclude fields (commonly used for_id) - The
_idfield is automatically included unless explicitly set to0 - You cannot mix inclusion and exclusion operators except for
_id
Conclusion
MongoDB's projection feature in find() provides the equivalent functionality to SQL's SELECT statement. Use field projection to retrieve only the necessary data and improve query performance.
Advertisements
