How to search for documents based on the value of adding two properties in MongoDB?


You can use aggregate framework for this. Here, we will get the sum and then match it to search for documents less than a particular number. Let us first create a collection with documents −

> db.searchDocumentsDemo.insertOne({"Value1":100,"Value2":560});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd3fe1eedc6604c74817ce9")
}
> db.searchDocumentsDemo.insertOne({"Value1":300,"Value2":150});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd3fe29edc6604c74817cea")
}
> db.searchDocumentsDemo.insertOne({"Value1":400,"Value2":200});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd3fe30edc6604c74817ceb")
}
> db.searchDocumentsDemo.insertOne({"Value1":190,"Value2":210});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd3fe45edc6604c74817cec")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5cd3fe1eedc6604c74817ce9"),
   "Value1" : 100,
   "Value2" : 560
}
{
   "_id" : ObjectId("5cd3fe29edc6604c74817cea"),
   "Value1" : 300,
   "Value2" : 150
}
{
   "_id" : ObjectId("5cd3fe30edc6604c74817ceb"),
   "Value1" : 400,
   "Value2" : 200
}
{
   "_id" : ObjectId("5cd3fe45edc6604c74817cec"),
   "Value1" : 190,
   "Value2" : 210
}

Following is the query to search for documents based on the value of adding two properties on the document −

> db.searchDocumentsDemo.aggregate([
...   { $project: {totalValue: { $add: [ "$Value1", "$Value2" ] } } },
...   { $match: {totalValue: {$lt: 500 }} }
... ]);

This will produce the following output −

{ "_id" : ObjectId("5cd3fe29edc6604c74817cea"), "totalValue" : 450 }
{ "_id" : ObjectId("5cd3fe45edc6604c74817cec"), "totalValue" : 400 }

Updated on: 30-Jul-2019

49 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements