Andres Espinosa
Andres Espinosa

Reputation: 402

MongoDb projection depending on another (boolean) field

I have a collection where every object has an anonymous boolean field. If it is true then I want the owner field to be filtered out (in my collection it's actually an array of owners).

Is there a way of including this restriction directly in the projection? Something like this:

MyCollection.find({}, {$if: {owners: anonymous} })

Upvotes: 0

Views: 173

Answers (1)

Andriy Simonov
Andriy Simonov

Reputation: 1288

You can use command like this:

MyCollection.aggregate([{$project: {owner: {$cond: ["$anonymous", null, "$owner"]}}}]);

It does not filter out the owner field, but sets it to null.

Upvotes: 1

Related Questions