bork
bork

Reputation: 1674

MongoDB return true if conditional query is met

I want to write a query that goes something like this in pseudo code: return true if value X is greater than value Y. In order to set a field within the data returned to either true or false. Like so: { xIsGreaterThanY: true, randomData: 123456, moreRandom: abcdefg}

But I have no idea how to write this type of query as I'm fairly new to MongoDB. Is this even possible to achieve?

I could of course just get all the data and do the calculation in JS or something, but I want to know if it is possible, just so I can learn more about MongoDB and all its magic. Also, it's quite nice to have the data as prepared as possible when it's returned from the database.

Upvotes: 0

Views: 619

Answers (1)

Kevin Smith
Kevin Smith

Reputation: 14466

Let's start with getting some values to play with;

> for(var i = 1; i <= 10; i++) { db.test.save({a : i, b: 10-i}); }
WriteResult({ "nInserted" : 1 })

> db.test.find()
{ "_id" : ObjectId("5a5c997b28e6f31805330889"), "a" : 1, "b" : 9 }
{ "_id" : ObjectId("5a5c997b28e6f3180533088a"), "a" : 2, "b" : 8 }
{ "_id" : ObjectId("5a5c997b28e6f3180533088b"), "a" : 3, "b" : 7 }
{ "_id" : ObjectId("5a5c997b28e6f3180533088c"), "a" : 4, "b" : 6 }
{ "_id" : ObjectId("5a5c997b28e6f3180533088d"), "a" : 5, "b" : 5 }
{ "_id" : ObjectId("5a5c997b28e6f3180533088e"), "a" : 6, "b" : 4 }
{ "_id" : ObjectId("5a5c997b28e6f3180533088f"), "a" : 7, "b" : 3 }
{ "_id" : ObjectId("5a5c997b28e6f31805330890"), "a" : 8, "b" : 2 }
{ "_id" : ObjectId("5a5c997b28e6f31805330891"), "a" : 9, "b" : 1 }
{ "_id" : ObjectId("5a5c997b28e6f31805330892"), "a" : 10, "b" : 0 }

We can now use the aggregation framework with a $cond:

> db.test.aggregate([
...     { $project: { aGreaterThanb: { $cond: { if: { $gt: [ "$a", "$b" ] }, then: true, else: false } } } }
...
... ]);
{ "_id" : ObjectId("5a5c997b28e6f31805330889"), "aGreaterThanb" : false }
{ "_id" : ObjectId("5a5c997b28e6f3180533088a"), "aGreaterThanb" : false }
{ "_id" : ObjectId("5a5c997b28e6f3180533088b"), "aGreaterThanb" : false }
{ "_id" : ObjectId("5a5c997b28e6f3180533088c"), "aGreaterThanb" : false }
{ "_id" : ObjectId("5a5c997b28e6f3180533088d"), "aGreaterThanb" : false }
{ "_id" : ObjectId("5a5c997b28e6f3180533088e"), "aGreaterThanb" : true }
{ "_id" : ObjectId("5a5c997b28e6f3180533088f"), "aGreaterThanb" : true }
{ "_id" : ObjectId("5a5c997b28e6f31805330890"), "aGreaterThanb" : true }
{ "_id" : ObjectId("5a5c997b28e6f31805330891"), "aGreaterThanb" : true }
{ "_id" : ObjectId("5a5c997b28e6f31805330892"), "aGreaterThanb" : true }

Upvotes: 1

Related Questions