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
Querying internal array size in MongoDB?
To query internal array size in MongoDB, use the $size operator. This operator returns the number of elements in an array field and can be used within aggregation pipelines to count array elements for specific documents.
Syntax
db.collection.aggregate([
{
$group: {
_id: yourObjectIdValue,
fieldName: { $first: { $size: "$arrayFieldName" } }
}
}
]);
Sample Data
Let's create a collection with employee documents containing technology arrays ?
db.internalArraySizeDemo.insertMany([
{
"EmployeeName": "Mike",
"EmployeeTechnology": ["Java Web Development", "Python Web Development"]
},
{
"EmployeeName": "Sam",
"EmployeeTechnology": ["C with Graphics", "Game Development with C++ Language", "MatLab"]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c6eff586fd07954a48906b2"),
ObjectId("5c6effcd6fd07954a48906b3")
]
}
View Sample Data
db.internalArraySizeDemo.find().pretty();
{
"_id": ObjectId("5c6eff586fd07954a48906b2"),
"EmployeeName": "Mike",
"EmployeeTechnology": [
"Java Web Development",
"Python Web Development"
]
}
{
"_id": ObjectId("5c6effcd6fd07954a48906b3"),
"EmployeeName": "Sam",
"EmployeeTechnology": [
"C with Graphics",
"Game Development with C++ Language",
"MatLab"
]
}
Example: Get Array Size for Specific Document
Query the array size for Mike's EmployeeTechnology array ?
db.internalArraySizeDemo.aggregate([
{
$group: {
_id: ObjectId("5c6eff586fd07954a48906b2"),
EmployeeTechnology_count: { $first: { $size: "$EmployeeTechnology" } }
}
}
]);
{ "_id": ObjectId("5c6eff586fd07954a48906b2"), "EmployeeTechnology_count": 2 }
Alternative: Using $project with $size
A more direct approach using $project to get array sizes for all documents ?
db.internalArraySizeDemo.aggregate([
{
$project: {
EmployeeName: 1,
TechnologyCount: { $size: "$EmployeeTechnology" }
}
}
]);
{ "_id": ObjectId("5c6eff586fd07954a48906b2"), "EmployeeName": "Mike", "TechnologyCount": 2 }
{ "_id": ObjectId("5c6effcd6fd07954a48906b3"), "EmployeeName": "Sam", "TechnologyCount": 3 }
Conclusion
The $size operator effectively counts array elements in MongoDB. Use it with $project for all documents or $group for specific document analysis within aggregation pipelines.
Advertisements
