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
Selected Reading
Count number of elements in an array with MongoDB?
To count number of elements in an array, use the aggregate framework. Let us first create a collection with documents −
>db.countNumberOfElementsDemo.insertOne({"UserMessage":["Hi","Hello","Bye","Awesome"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cef8ec2ef71edecf6a1f6a1")
}
Display all documents from a collection with the help of find() method −
> db.countNumberOfElementsDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5cef8ec2ef71edecf6a1f6a1"),
"UserMessage" : [
"Hi",
"Hello",
"Bye",
"Awesome"
]
}
Following is the query to count number of elements in an array −
> db.countNumberOfElementsDemo.aggregate({$project: { NumberOfElements: { $size:"$UserMessage" }}})
This will produce the following output −
{ "_id" : ObjectId("5cef8ec2ef71edecf6a1f6a1"), "NumberOfElements" : 4 } Advertisements
