如何使用 MongoDB 来查找所有具有某个字段的文档,而不管该字段的值是什么?
若要使用 MongoDB 查找具有某个字段的所有文档,而不管该字段的值是什么,请使用 $exists 运算符。以下是语法
db.yourCollectionName.find({yourFieldName:{$exists:true}});让我们创建一个包含文档的集合
>db.findAllDocumentWhichHaveFieldDemo.insertOne({"StudentName":"John","StudentAge":null});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9d1d60a629b87623db1b22")
}
>db.findAllDocumentWhichHaveFieldDemo.insertOne({"StudentName":"Larry","StudentAge":null});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9d1d70a629b87623db1b23")
}
>db.findAllDocumentWhichHaveFieldDemo.insertOne({"StudentName":"Chris","StudentAge":""});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9d1d7ba629b87623db1b24")
}
>db.findAllDocumentWhichHaveFieldDemo.insertOne({"StudentName":"Robert","StudentAge":""});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9d1d81a629b87623db1b25")
}以下是对所有文档执行查询的方法,该方法使用 find() 来显示集合中具有学生姓名字段的文档
> db.findAllDocumentWhichHaveFieldDemo.find().pretty();
这将产生以下输出
{
"_id" : ObjectId("5c9d1d60a629b87623db1b22"),
"StudentName" : "John",
"StudentAge" : null
}
{
"_id" : ObjectId("5c9d1d70a629b87623db1b23"),
"StudentName" : "Larry",
"StudentAge" : null
}
{
"_id" : ObjectId("5c9d1d7ba629b87623db1b24"),
"StudentName" : "Chris",
"StudentAge" : ""
}
{
"_id" : ObjectId("5c9d1d81a629b87623db1b25"),
"StudentName" : "Robert",
"StudentAge" : ""
}以下是使用 MongoDB 查找具有某个字段的所有文档的查询,而不管该字段的值是什么
> db.findAllDocumentWhichHaveFieldDemo.find({StudentAge:{$exists:true}});这将产生以下输出
{ "_id" : ObjectId("5c9d1d60a629b87623db1b22"), "StudentName" : "John", "StudentAge" : null }
{ "_id" : ObjectId("5c9d1d70a629b87623db1b23"), "StudentName" : "Larry", "StudentAge" : null }
{ "_id" : ObjectId("5c9d1d7ba629b87623db1b24"), "StudentName" : "Chris", "StudentAge" : "" }
{ "_id" : ObjectId("5c9d1d81a629b87623db1b25"), "StudentName" : "Robert", "StudentAge" : "" }如果您不希望结果中显示“StudentName”字段,请使用以下查询
>db.findAllDocumentWhichHaveFieldDemo.find({},{StudentName:0},{StudentAge:{$exists:true}});这将产生以下输出
{ "_id" : ObjectId("5c9d1d60a629b87623db1b22"), "StudentAge" : null }
{ "_id" : ObjectId("5c9d1d70a629b87623db1b23"), "StudentAge" : null }
{ "_id" : ObjectId("5c9d1d7ba629b87623db1b24"), "StudentAge" : "" }
{ "_id" : ObjectId("5c9d1d81a629b87623db1b25"), "StudentAge" : "" }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP