MongoDB Query to select records having a given key?

MongoDBDatabaseBig Data Analytics

To select records having a given key, you can use $exists operator. The syntax is as follows −

db.yourCollectionName.find( { yourFieldName: { $exists : true } } ).pretty();

To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows −

> 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")
}

Display all documents from a collection with the help of find() method. The query is as follows −

> db.selectRecordsHavingKeyDemo.find().pretty();

The following is the output −

{
   "_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
}

Here is the query to select records having a given key −

> db.selectRecordsHavingKeyDemo.find( { StudentMathMarks : { $exists : true } } ).pretty();

The following is the output −

{
   "_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
}
raja
Published on 29-Mar-2019 11:13:30
Advertisements