0

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.

2

1 Answer 1

1

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 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.