Eumendies
Eumendies

Reputation: 73

How to implement the follow RMDB query in MongoDB

My team started to use MongoDB now and wanna migrate some sql to Mongo. For example, I have an order table and has the fields price and quanty.I want to query the price*quanty greater than 100. sql is like below

select * from Order where price * quanty > 100;

How to use "price * quanty" this kind query in Mongo?

Thanks.

Upvotes: 1

Views: 40

Answers (2)

Mike
Mike

Reputation: 5142

As JohnnyHK points out you can use $expr, but as an alternative you can also use aggregation to first create a new field that is the product of two other fields:

db.orders.aggregate([
     { $set: { product: { $multiply: [ "$price", "$quantity" ] } } }
   ])

Note: $set is new in 4.2 and just an alias for $addFields

Then add a $match stage that only matches documents with the new product field meeting your condition:

db.orders.aggregate([
     { $set: { product: { $multiply: [ "$price", "$quantity" ] } } },
     { $match: { product: { $gt: 100 } } }
   ])

Upvotes: 0

JohnnyHK
JohnnyHK

Reputation: 311855

You can do this by using the $expr operator to use aggregation expressions within your query:

db.orders.find({
  $expr: {
    $gt: [
      { $multiply: ["$price", "$quantity"] },
      100
    ]
  }
})

Upvotes: 1

Related Questions