skip to Main Content

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?

2

Answers


  1. 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
            }
          }
        }
      }
    })
    
    Login or Signup to reply.
  2. you can do this using with aggregate.

    db.orders.aggregate([
         {
            $unwind:"$detail"
         },
         {
            $match:{
                  "detail.price":{$gt:0}
            }
         }
    ]); 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search