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:
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.
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}
}
}
]);