Reputation: 697
I was recently asked this question: If I have a document in the collection like {a: 1, b: 2}, how do I filter for all documents where a/b >= 0.5 ? Here is my solution.
Upvotes: 0
Views: 95
Reputation: 697
Suppose I have a collection "data" of the following format — sample documents below:
{ "_id" : ObjectId("533e46e99710181b60737702"), "a" : 65, "b" : 25.3 }
{ "_id" : ObjectId("533e46e99710181b60737703"), "a" : 39.1, "b" : 66 }
{ "_id" : ObjectId("533e46e99710181b60737704"), "a" : 31.7, "b" : 96.3 }
{ "_id" : ObjectId("533e46e99710181b60737705"), "a" : 48.6, "b" : 75.1 }
{ "_id" : ObjectId("533e46e99710181b60737706"), "a" : 20.8, "b" : 97.3 }
Here is the query:
> db.data.aggregate([ { $project: { t: { $divide: [ "$a", "$b" ] } } },
{ $match: { t: { $gt: 20} } } ])
{
"result" : [
{
"_id" : ObjectId("533e46e99710181b6073770d"),
"t" : 40.75
},
],
"ok" : 1
}
Upvotes: 2