Home > Software design >  how to reference document's field value in query?
how to reference document's field value in query?

Time:06-01

documents look like this:

[{
  quantity, 15,
  limit: 15
},
{
  quantity: 4,
  limit: 5
},
{
  quantity: 3,
  limit: 3,
}]

I need to find a document whose quantity is less than limit. All documents have different quantities and limits.

How can I find a document whose quantity is less than its limit without knowing document's limit?

CodePudding user response:

Work with $expr to access the field value and use of aggregation operator.

db.collection.find({
  $expr: {
    $lt: [
      "$quantity",
      "$limit"
    ]
  }
})

Sample Mongo Playground (Query)


For aggregation query:

db.collection.aggregate([
  {
    $match: {
      $expr: {
        $lt: [
          "$quantity",
          "$limit"
        ]
      }
    }
  }
])

Sample Mongo Playground (Aggregation Query)

  • Related