Using $redact in MongoDB aggregate?


The $redact restricts the contents of the documents based on information stored in the documents themselves. You can use $cond along with $redact in aggregate. Let us create a collection with documents −

> db.demo546.insertOne({"Value1":10,"Value2":20});{
   "acknowledged" : true, "insertedId" : ObjectId("5e8e263f9e5f92834d7f05d7")
}
> db.demo546.insertOne({"Value1":40,"Value2":30,Value3:50});{
   "acknowledged" : true, "insertedId" : ObjectId("5e8e26549e5f92834d7f05d8")
}
> db.demo546.insertOne({"Value1":100,"Value2":200,Value3:null});{
   "acknowledged" : true, "insertedId" : ObjectId("5e8e26619e5f92834d7f05d9")
}
> db.demo546.insertOne({"Value1":400,"Value2":1000,Value3:null});{
   "acknowledged" : true, "insertedId" : ObjectId("5e8e26e09e5f92834d7f05da")
}
> db.demo546.insertOne({"Value1":400,"Value2":200,Value3:null});{
   "acknowledged" : true, "insertedId" : ObjectId("5e8e26f59e5f92834d7f05db")
}
> db.demo546.insertOne({"Value1":400,"Value2":1000,Value3:60});{
   "acknowledged" : true, "insertedId" : ObjectId("5e8e27159e5f92834d7f05dc")
}

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

> db.demo546.find();

This will produce the following output −

{ "_id" : ObjectId("5e8e263f9e5f92834d7f05d7"), "Value1" : 10, "Value2" : 20 }
{ "_id" : ObjectId("5e8e26549e5f92834d7f05d8"), "Value1" : 40, "Value2" : 30, "Value3" : 50 }
{ "_id" : ObjectId("5e8e26619e5f92834d7f05d9"), "Value1" : 100, "Value2" : 200, "Value3" : null }
{ "_id" : ObjectId("5e8e26e09e5f92834d7f05da"), "Value1" : 400, "Value2" : 1000, "Value3" : null }
{ "_id" : ObjectId("5e8e26f59e5f92834d7f05db"), "Value1" : 400, "Value2" : 200, "Value3" : null }
{ "_id" : ObjectId("5e8e27159e5f92834d7f05dc"), "Value1" : 400, "Value2" : 1000, "Value3" : 60 }

Following is the query to $exists with $redact with MongoDB aggregate −

> db.demo546.aggregate( { "$redact": { "$cond": { "if": { "$and": [ {
   "$lt": [ "$Value1", "$Value2" ] }, { "$ifNull": [ "$Value3", false ] } ] },
   "then": "$$KEEP", "else": "$$PRUNE" } }
} );

This will produce the following output −

{ "_id" : ObjectId("5e8e27159e5f92834d7f05dc"), "Value1" : 400, "Value2" : 1000, "Value3" : 60 }

Updated on: 14-May-2020

452 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements