Check whether field exist in MongoDB or not?


You can use $exists operator for this. Let us first create a collection with documents −

>db.checkFieldExistsDemo.insertOne({"StudentFirstName":"John","StudentGender":"Male","StudentMongoDBScore":89});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd909611a844af18acdffbd")
}
>db.checkFieldExistsDemo.insertOne({"StudentFirstName":"Emma","StudentGender":"Female","StudentMongoDBScore":58});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd909781a844af18acdffbe")
}
>db.checkFieldExistsDemo.insertOne({"StudentFirstName":"Carol","StudentGender":"Male","StudentMongoDBScore":77});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd909871a844af18acdffbf")
}
>db.checkFieldExistsDemo.insertOne({"StudentFirstName":"David","StudentMongoDBScore":98});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd909a31a844af18acdffc0")
}

Following is the query to display all documents from a collection with the help of find() method −

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

This will produce the following output −

{
   "_id" : ObjectId("5cd909611a844af18acdffbd"),
   "StudentFirstName" : "John",
   "StudentGender" : "Male",
   "StudentMongoDBScore" : 89
}
{
   "_id" : ObjectId("5cd909781a844af18acdffbe"),
   "StudentFirstName" : "Emma",
   "StudentGender" : "Female",
   "StudentMongoDBScore" : 58
}
{
   "_id" : ObjectId("5cd909871a844af18acdffbf"),
   "StudentFirstName" : "Carol",
   "StudentGender" : "Male",
   "StudentMongoDBScore" : 77
}
{
   "_id" : ObjectId("5cd909a31a844af18acdffc0"),
   "StudentFirstName" : "David",
   "StudentMongoDBScore" : 98
}

Following is the query to check whether a field exist in MongoDB −

> db.checkFieldExistsDemo.find({"StudentMongoDBScore":98, "StudentGender":{"$exists": false}},{'StudentFirstName': 1, '_id':0});

This will produce the following output −

{ "StudentFirstName" : "David" }
raja
Published on 13-Jun-2019 14:36:42
Advertisements