- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Query for documents where array size is greater than 1 in MongoDB?
You can use length to query for documents where array size is greater than 1:
db.yourCollectionName.find({$where:"this.yourArrayDocumentName.length > 1"}).pretty();
To understand the above syntax, let us create a collection with some documents. The query is as follows to create a collection with documents:
>db.arrayLengthGreaterThanOne.insertOne({"StudentName":"Larry","StudentTechnicalSubje ct":["Java","C","C++"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c6d6c4c0c3d5054b766a76a") } >db.arrayLengthGreaterThanOne.insertOne({"StudentName":"Maxwell","StudentTechnicalSu bject":["MongoDB"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c6d6c660c3d5054b766a76b") } >db.arrayLengthGreaterThanOne.insertOne({"StudentName":"Maxwell","StudentTechnicalSu bject":["MySQL","SQL Server","PL/SQL"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c6d6c800c3d5054b766a76c") }
Display all documents from a collection with the help of find() method. The query is as follows:
> db.arrayLengthGreaterThanOne.find().pretty();
The following is the output:
{ "_id" : ObjectId("5c6d6c4c0c3d5054b766a76a"), "StudentName" : "Larry", "StudentTechnicalSubject" : [ "Java", "C", "C++" ] } { "_id" : ObjectId("5c6d6c660c3d5054b766a76b"), "StudentName" : "Maxwell", "StudentTechnicalSubject" : [ "MongoDB" ] } { "_id" : ObjectId("5c6d6c800c3d5054b766a76c"), "StudentName" : "Maxwell", "StudentTechnicalSubject" : [ "MySQL", "SQL Server", "PL/SQL" ] }
Here is the query for documents where array size is greater than 1. The below query will give all documents where array size is greater than 1:
> db.arrayLengthGreaterThanOne.find({$where:"this.StudentTechnicalSubject.length > 1"}).pretty();
The following is the output:
{ "_id" : ObjectId("5c6d6c4c0c3d5054b766a76a"), "StudentName" : "Larry", "StudentTechnicalSubject" : [ "Java", "C", "C++" ] } { "_id" : ObjectId("5c6d6c800c3d5054b766a76c"), "StudentName" : "Maxwell", "StudentTechnicalSubject" : [ "MySQL", "SQL Server", "PL/SQL" ] }
Advertisements