Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Querying internal array size in MongoDB?
You can use the $size operator for internal array size in MongoDB. The syntax is as follows:
db.internalArraySizeDemo.aggregate(
[
{
$group: {
_id:yourObjectIdValue,
anyFieldName: {$first: {$size: "$yourArrayName" }}
}
}
]
);
To understand the above syntax, let us create a collection with some documents. The query to create a collection with documents are as follows:
>db.internalArraySizeDemo.insertOne({"EmployeeName":"Mike","EmployeeTechnology":["Jav
a Web Development","Python Web Development"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6eff586fd07954a48906b2")
}
> db.internalArraySizeDemo.insertOne({"EmployeeName":"Sam","EmployeeTechnology":["C
with Graphics","Game Development with C++ Language","MatLab"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6effcd6fd07954a48906b3")
}
Display all documents from a collection with the help of find() method. The query is as follows:
> db.internalArraySizeDemo.find().pretty();
The following is the output:
{
"_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"
]
}
Here is the query to get the internal array size with the help of $size operator:
> db.internalArraySizeDemo.aggregate(
... [
... {
... $group: {
... _id:ObjectId("5c6eff586fd07954a48906b2"),
... EmployeeTechnology_count: {$first: {$size: "$EmployeeTechnology" }}
... }
... }
... ]
... );
The following is the output:
{ "_id" : ObjectId("5c6eff586fd07954a48906b2"), "EmployeeTechnology_count" : 2 }Advertisements