Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Remove or Limit fields conditional aggregation

I am having some issue writing a find/aggregate mongo query where my requirement is to get all the documents but having condition like:

Suppose I have 2 documents:

{
  _id: 5ccaa76939d95d395791efd2,
  name: 'John Doe',
  email: '[email protected]',
  private: true
}

{
  _id: 5ccaa76939d95d395791efd2,
  name: 'Jane Doe',
  email: '[email protected]',
  private: false
} 

Now the query I am trying to get my head around is if the field private is true then when I query I must get all documents except email fields not included if private is true, like this:

{
 _id: 5ccaa76939d95d395791efd2,
 name: 'John Doe',
 private: true
}

{
 _id: 5ccaa76939d95d395791efd2,
 name: 'Jane Doe',
 email: '[email protected]',
 private: false
} 

Tried $redact, $cond, $$PRUNE, $$DESCEND in aggregate() as well as came across $$REMOVE (looks like it is newest feature) but unable to get the required output. Please help me out with the Query

like image 841
rohitpaniker Avatar asked Mar 24 '26 04:03

rohitpaniker


1 Answers

You can use $$REMOVE to remove a field from returned documents.

db.collection.aggregate([ 
  { "$addFields": {
    "email": {
      "$cond": [
        { "$eq": ["$private", true] },
        "$$REMOVE",
        "$email"
      ]
    }
  }}
])

MongoPlayground

like image 128
Ashh Avatar answered Mar 27 '26 05:03

Ashh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!