Search by property name for any document with that property in MongoDB?


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

> db.searchByPropertyName.insertOne({"FirstName":"Larry","Age":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbaf7af7219729fde21ddb5")
}
> db.searchByPropertyName.insertOne({"FirstName":null,"Age":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbaf7b97219729fde21ddb6")
}
> db.searchByPropertyName.insertOne({"FirstName":"John","Age":22});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbaf7c57219729fde21ddb7")
}
> db.searchByPropertyName.insertOne({"FirstName":null,"Age":25});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbaf7d07219729fde21ddb8")
}
> db.searchByPropertyName.insertOne({"FirstName":"David","Age":20});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbaf7df7219729fde21ddb9")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5cbaf7af7219729fde21ddb5"),
   "FirstName" : "Larry",
   "Age" : 23
}
{
   "_id" : ObjectId("5cbaf7b97219729fde21ddb6"),
   "FirstName" : null,
   "Age" : 21
}
{
   "_id" : ObjectId("5cbaf7c57219729fde21ddb7"),
   "FirstName" : "John",
   "Age" : 22
}
{
   "_id" : ObjectId("5cbaf7d07219729fde21ddb8"),
   "FirstName" : null,
   "Age" : 25
}
{
   "_id" : ObjectId("5cbaf7df7219729fde21ddb9"),
   "FirstName" : "David",
   "Age" : 20
}

Following is the query to search by property name for any document with that property −

> db.searchByPropertyName.find({FirstName: { $ne : null } } ).pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cbaf7af7219729fde21ddb5"),
   "FirstName" : "Larry",
   "Age" : 23
}
{
   "_id" : ObjectId("5cbaf7c57219729fde21ddb7"),
   "FirstName" : "John",
   "Age" : 22
}
{
   "_id" : ObjectId("5cbaf7df7219729fde21ddb9"),
   "FirstName" : "David",
   "Age" : 20
}

Updated on: 30-Jul-2019

173 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements