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
How to count items in array with MongoDB?
To count items in array, use length. Let us create a collection with documents −
> db.demo440.insertOne(
... {
... "Name":"Chris",
... "ListOfFriends":["John","Sam","Mike"]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e78c63cbbc41e36cc3caeb5")
}
>
> db.demo440.insertOne(
... {
... "Name":"David",
... "ListOfFriends":["Mike","Bob","Carol"]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e78c63cbbc41e36cc3caeb6")
}
Display all documents from a collection with the help of find() method −
> db.demo440.find();
This will produce the following output −
{ "_id" : ObjectId("5e78c63cbbc41e36cc3caeb5"), "Name" : "Chris", "ListOfFriends" : [ "John", "Sam", "Mike" ] }
{ "_id" : ObjectId("5e78c63cbbc41e36cc3caeb6"), "Name" : "David", "ListOfFriends" : [ "Mike", "Bob", "Carol" ] }
Following is the query to count items in array −
>db.demo440.findOne({'Name':'David'}).ListOfFriends.length;
This will produce the following output −
3
Advertisements