要选择具有给定键的记录,可以使用$exists运算符。语法如下-
db.yourCollectionName.find( { yourFieldName: { $exists : true } } ).pretty();
为了理解上述语法,让我们用文档创建一个集合。使用文档创建集合的查询如下-
> db.selectRecordsHavingKeyDemo.insertOne({"StudentName":"John","StudentAge":21,"StudentMathMarks":78});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8b7be780f10143d8431e0f")
}
> db.selectRecordsHavingKeyDemo.insertOne({"StudentName":"Carol","StudentMathMarks":89});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8b7bfc80f10143d8431e10")
}
> db.selectRecordsHavingKeyDemo.insertOne({"StudentName":"Sam","StudentAge":26,"StudentMathMarks":89});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8b7c1280f10143d8431e11")
}
> db.selectRecordsHavingKeyDemo.insertOne({"StudentName":"Sam","StudentMathMarks":98});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8b7c2180f10143d8431e12")
}
在find()
method的帮助下显示集合中的所有文档。查询如下-
> db.selectRecordsHavingKeyDemo.find().pretty();
以下是输出-
{
"_id" : ObjectId("5c8b7be780f10143d8431e0f"),
"StudentName" : "John",
"StudentAge" : 21,
"StudentMathMarks" : 78
}
{
"_id" : ObjectId("5c8b7bfc80f10143d8431e10"),
"StudentName" : "Carol",
"StudentMathMarks" : 89
}
{
"_id" : ObjectId("5c8b7c1280f10143d8431e11"),
"StudentName" : "Sam",
"StudentAge" : 26,
"StudentMathMarks" : 89
}
{
"_id" : ObjectId("5c8b7c2180f10143d8431e12"),
"StudentName" : "Sam",
"StudentMathMarks" : 98
}
这是查询以选择具有给定键的记录-
> db.selectRecordsHavingKeyDemo.find( { StudentMathMarks : { $exists : true } } ).pretty();
以下是输出-
{
"_id" : ObjectId("5c8b7be780f10143d8431e0f"),
"StudentName" : "John",
"StudentAge" : 21,
"StudentMathMarks" : 78
}
{
"_id" : ObjectId("5c8b7bfc80f10143d8431e10"),
"StudentName" : "Carol",
"StudentMathMarks" : 89
}
{
"_id" : ObjectId("5c8b7c1280f10143d8431e11"),
"StudentName" : "Sam",
"StudentAge" : 26,
"StudentMathMarks" : 89
}
{
"_id" : ObjectId("5c8b7c2180f10143d8431e12"),
"StudentName" : "Sam",
"StudentMathMarks" : 98
}