Find MongoDB records where array field is not empty?

MongoDBDatabaseBig Data Analytics

You can use $ne(Not Equal) operator for this. To understand the concept, let us create a collection with document. The query to create a collection with document is as follows −

> db.arrayFieldIsNotEmptyDemo.insertOne({"StudentName":"Larry","StudentTechnicalSubject":["Java","C"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c76fe2f1e9c5dd6f1f78291")
}
> db.arrayFieldIsNotEmptyDemo.insertOne({"StudentName":"Mike","StudentTechnicalSubject":[]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c76fe3b1e9c5dd6f1f78292")
}
> db.arrayFieldIsNotEmptyDemo.insertOne({"StudentName":"Sam","StudentTechnicalSubject":["MongoDB"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c76fe491e9c5dd6f1f78293")
}
> db.arrayFieldIsNotEmptyDemo.insertOne({"StudentName":"Carol","StudentTechnicalSubject":[]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c76fe521e9c5dd6f1f78294")
}
> db.arrayFieldIsNotEmptyDemo.insertOne({"StudentName":"David","StudentTechnicalSubject":["MySQL","SQL Server"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c76fe661e9c5dd6f1f78295")
}

Display all documents from a collection with the help of find() method. The query is as follows −

> db.arrayFieldIsNotEmptyDemo.find().pretty();

Output

{
   "_id" : ObjectId("5c76fe2f1e9c5dd6f1f78291"),
   "StudentName" : "Larry",
   "StudentTechnicalSubject" : [
      "Java",
      "C"
   ]
}
{
   "_id" : ObjectId("5c76fe3b1e9c5dd6f1f78292"),
   "StudentName" : "Mike",
   "StudentTechnicalSubject" : [ ]
}
{
   "_id" : ObjectId("5c76fe491e9c5dd6f1f78293"),
   "StudentName" : "Sam",
   "StudentTechnicalSubject" : [
      "MongoDB"
   ]
}
{
   "_id" : ObjectId("5c76fe521e9c5dd6f1f78294"),
   "StudentName" : "Carol",
   "StudentTechnicalSubject" : [ ]
}
{
   "_id" : ObjectId("5c76fe661e9c5dd6f1f78295"),
   "StudentName" : "David",
   "StudentTechnicalSubject" : [
      "MySQL",
      "SQL Server"
   ]
}

Here is the query to find MongoDB records where array field is not empty −

> db.arrayFieldIsNotEmptyDemo.find({StudentTechnicalSubject:{$exists:true,$ne:[]}}).pretty();

Output

{
   "_id" : ObjectId("5c76fe2f1e9c5dd6f1f78291"),
   "StudentName" : "Larry",
   "StudentTechnicalSubject" : [
      "Java",
      "C"
   ]
}
{
   "_id" : ObjectId("5c76fe491e9c5dd6f1f78293"),
   "StudentName" : "Sam",
   "StudentTechnicalSubject" : [
      "MongoDB"
   ]
}
{
   "_id" : ObjectId("5c76fe661e9c5dd6f1f78295"),
   "StudentName" : "David",
   "StudentTechnicalSubject" : [
      "MySQL",
      "SQL Server"
   ]
}
raja
Published on 28-Mar-2019 11:01:17
Advertisements