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
You can use $$REMOVE to remove a field from returned documents.
db.collection.aggregate([
{ "$addFields": {
"email": {
"$cond": [
{ "$eq": ["$private", true] },
"$$REMOVE",
"$email"
]
}
}}
])
MongoPlayground
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With