Home > Mobile >  select docs where all items in an array match a criteria
select docs where all items in an array match a criteria

Time:05-21

Consider this data in mongodb:

{
        "ordernumber" : "161288",
        "detail" : [
                {
                        "articlenumber" : "1619",
                        "price" : 10,
                },
                {
                        "articlenumber" : "1620",
                        "price" : 0,
                }
        ]
}

So basic order data with an array of articles in them.

Now I want to query all orders with where ALL items in detail have a price > 0. So the above one is not selected as 1 item has zero.

This errors ($all needs an array):

db.orders.find({'detail.price': { $all: { $gt: 0 }}})

this finds all orders if at least one price > 0.

db.orders.find({'detail.price': { $gt: 0 }})

How is that possible? Select only docs where all items in an array match a criteria?

CodePudding user response:

playground

db.collection.find({
  detail: {
    $not: {
      "$elemMatch": {
        price: { //Negate the condition
          $lt: 0
        }
      }
    }
  }
})

By this way, you can find all the matching docs with the given condition.

To get lt value

db.collection.find({
  detail: {
    $not: {
      "$elemMatch": {
        price: {
          $gt: 3
        }
      }
    }
  }
})

CodePudding user response:

you can do this using with aggregate.

db.orders.aggregate([
     {
        $unwind:"$detail"
     },
     {
        $match:{
              "detail.price":{$gt:0}
        }
     }
]); 
  • Related