要使用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" : "" }