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
Find MongoDB records where array field is not empty?
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"
]
} Advertisements
