在数组字段不为空的情况下查找MongoDB记录?

您可以为此使用$ne(Not Equal)运算符。为了理解这个概念,让我们创建一个带有文档的集合。创建带有文档的集合的查询如下-

> 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")
}

find()method的帮助下显示集合中的所有文档。查询如下-

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

输出结果

{
   "_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"
   ]
}

这是查找MongoDB记录的查询,其中数组字段不为空-

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

输出结果

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