Query for documents where array size is greater than 1 in MongoDB?

MongoDBDatabaseBig Data Analytics

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"
   ]
}
raja
Published on 18-Mar-2019 16:05:30
Advertisements