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 query all items in MongoDB?
To query all items in a MongoDB collection, use the find() method. This method retrieves all documents from a collection when called without parameters, or you can specify query criteria and projection options to filter results.
Syntax
db.collection.find() db.collection.find(query, projection)
Create Sample Data
Let us first create a collection with documents ?
db.queryAllItemsDemo.insertMany([
{
"StudentDetails": {
"StudentName": "John",
"StudentSubject": ["MongoDB", "MySQL"],
"StudentSubjectPrice": [4000, 6000]
},
"OtherDetails": {
"UserAge": 29,
"UserCountryName": "US"
}
},
{
"StudentDetails": {
"StudentName": "Alice",
"StudentSubject": ["Python", "Java"],
"StudentSubjectPrice": [3500, 5500]
},
"OtherDetails": {
"UserAge": 25,
"UserCountryName": "Canada"
}
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cef74ecef71edecf6a1f69f"),
ObjectId("5cef74ecef71edecf6a1f6a0")
]
}
Method 1: Query All Documents
Display all documents from a collection with the help of find() method ?
db.queryAllItemsDemo.find().pretty();
{
"_id": ObjectId("5cef74ecef71edecf6a1f69f"),
"StudentDetails": {
"StudentName": "John",
"StudentSubject": [
"MongoDB",
"MySQL"
],
"StudentSubjectPrice": [
4000,
6000
]
},
"OtherDetails": {
"UserAge": 29,
"UserCountryName": "US"
}
}
{
"_id": ObjectId("5cef74ecef71edecf6a1f6a0"),
"StudentDetails": {
"StudentName": "Alice",
"StudentSubject": [
"Python",
"Java"
],
"StudentSubjectPrice": [
3500,
5500
]
},
"OtherDetails": {
"UserAge": 25,
"UserCountryName": "Canada"
}
}
Method 2: Query with Projection
Query all items but display only specific fields using projection ?
db.queryAllItemsDemo.find({}, {StudentDetails: 1}).pretty();
{
"_id": ObjectId("5cef74ecef71edecf6a1f69f"),
"StudentDetails": {
"StudentName": "John",
"StudentSubject": [
"MongoDB",
"MySQL"
],
"StudentSubjectPrice": [
4000,
6000
]
}
}
{
"_id": ObjectId("5cef74ecef71edecf6a1f6a0"),
"StudentDetails": {
"StudentName": "Alice",
"StudentSubject": [
"Python",
"Java"
],
"StudentSubjectPrice": [
3500,
5500
]
}
}
Conclusion
The find() method is the primary way to query all items in MongoDB. Use it without parameters to get all documents, or add projection to control which fields are returned in the results.
Advertisements
