在 MongoDB 中如何查找数组字段不为空的记录?
你可以使用 $ne(不等于)运算符。为了理解这一概念,让我们创建一个带有文档的集合。创建含有该文档的集合的查询如下 −
> 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() 方法显示所有文档。查询如下 −
> 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" ] }
广告