user2612481
user2612481

Reputation: 39

mongodb find query conditional return value

I can do a find in mongodb like:

db.user.find({ "show": true}, { firstname: 1, lastname: 1, email:1 })

Now I'd like to be a little more specific to let people hide their email address. So what I'd like is to query if "show":true then get firstname:1, lastname:1 AND (email:1 iff show_email:true)

worst case I can take all the info and filter it out on the back end with a map function but I wondered if there was a nice query-able way??

Upvotes: 1

Views: 345

Answers (2)

JohnnyHK
JohnnyHK

Reputation: 312095

The truthiness of the projection object's fields are all that matter, so you can just do it as:

db.user.find({ "show": true }, { firstname: 1, lastname: 1, email: show_email })

Upvotes: 1

Works On Mine
Works On Mine

Reputation: 1131

Since you didnt specify any driver specification, I am betting on this, the MongoShell

if(show_email){
   db.user.find({ "show": true}, { firstname: 1, lastname: 1, email:1 })
}
else{
   db.user.find({ "show": true}, { firstname: 1, lastname: 1})
}

Upvotes: 0

Related Questions