MongoDB 查询以选择具有给定键的记录?
要选择具有给定键的记录,可以使用 $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() 方法从集合中显示所有文档。查询如下−
> 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 }
广告