How to compare two fields in aggregation filter with MongoDB?

MongoDBDatabaseBig Data Analytics

For this, use aggregate() along with $filter. Let us create a collection with documents −

> db.demo137.insertOne(
...    {
...       Name1:"Chris",
...       Name2:"David",
...       Detail1:[
...          {_id:"John", Name3:"Chris"},
...          {_id:"Chris", Name3:"Chris"},
...       ],
...       Detail2:[{_id:"David", Name3:"Chris"},
...       {_id:"Carol", Name3:"Chris"},
...       {_id:"John", Name3:"Chris"}]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e31b4cefdf09dd6d08539a0")
}

Display all documents from a collection with the help of find() method −

> db.demo137.find();

This will produce the following output −

{
   "_id" : ObjectId("5e31b4cefdf09dd6d08539a0"), "Name1" : "Chris", "Name2" : "David", "Detail1" : [
      { "_id" : "John", "Name3" : "Chris" },
      { "_id" : "Chris", "Name3" : "Chris" } ], "Detail2" : [ { "_id" : "David", "Name3" : "Chris" },
      { "_id" : "Carol", "Name3" : "Chris" }, { "_id" : "John", "Name3" : "Chris" }
   ]
}

Following is the query to compare two fields in aggregation filter −

> db.demo137.aggregate([
...    {
...       $project: {
...          _id: 0,
...          Name1: 1,
...          Name2: 2,
...          Detail1: {
...             $filter: {
...                input: "$Detail1",
...                as: "out",
...                cond: {
...                   $eq: ["$$out._id", "$Name1" ]
...                }
...             }
...          },
...          Detail2: {
...             $filter: {
...                input: "$Detail2",
...                as: "out",
...                cond: {
...                   $eq: ["$$out._id", "$Name2" ]
...                }
...             }
...          }
...       }
...    }
... ])

This will produce the following output −

{
   "Name1" : "Chris", "Name2" : "David", "Detail1" : [
      { "_id" : "Chris", "Name3" : "Chris" } ], "Detail2" : [ { "_id" : "David", "Name3" : "Chris" }
   ] 
}
raja
Published on 31-Mar-2020 15:54:39
Advertisements