Kartikeya Mishra
Kartikeya Mishra

Reputation: 126

Sum or Difference operation of two keys in document using Mongoengine

I have defined a model like

Class Orders(Document):
     orderAmount = fields.FloatField()
     cashbackAmount = fields.FloatField()
     meta = {'strict': False}

I want to get all orders where (orderAmount - cashbackAmount value > 500). I am using Mongoengine and using that I want to perform this operation. I am not using Django Framework so I cannot use solutions of that.

Upvotes: 0

Views: 316

Answers (1)

mateuszb
mateuszb

Reputation: 1143

Let's approach this if you had to do this without Mongoengine. You would start by dividing this problem into two steps

1) How to get the difference between two fields and output it as the new field?

2) How to filter all the documents based on that field's value?

You can see that it consists of several steps, so it looks like a great use case for the aggregation framework.

The first problem can be solved using addFields and subtract operators.

{$addFields: {difference: {$subtract: ["$a", "$b"]}}}

what can be translated into "for every document add a new field called difference where difference=a-b".

The second problem is a simple filtering:

{$match: {difference:{$gt: 500}}}

"give me all documents where difference field is greater than 500"

So the whole query in MongoDB would look like this

db.collectionName.aggregate([{$addFields: {difference: {$subtract: ["$a", "$b"]}}}, {$match: {difference:{$gt: 500}}}])

Now we have to translate it into Mongoengine. It turns out that there is aggregate method defined, so we can easily make small adjustments to make this query work.

Diff.objects.aggregate({"$addFields": {"difference": {"$subtract": ["$a", "$b"]}}}, {"$match": {"difference":{"$gt": 500}}})

As a result, you get CommandCursor. You can interact with that object or just convert it to the list, to get a list of dictionaries.

Upvotes: 1

Related Questions