select 个数组中的所有项目都符合条件的文档
select docs where all items in an array match a criteria
考虑 mongodb 中的数据:
{
"ordernumber" : "161288",
"detail" : [
{
"articlenumber" : "1619",
"price" : 10,
},
{
"articlenumber" : "1620",
"price" : 0,
}
]
}
基本订单数据,其中包含一系列文章。
现在我想查询所有订单,其中所有商品的详细价格都> 0。因此未选择上面的订单,因为 1 件商品的价格为零。
这个错误($all 需要一个数组):
db.orders.find({'detail.price': { $all: { $gt: 0 }}})
如果至少有一个价格 > 0,这会找到所有订单。
db.orders.find({'detail.price': { $gt: 0 }})
这怎么可能? Select 只有数组中的所有项目都符合条件的文档?
db.collection.find({
detail: {
$not: {
"$elemMatch": {
price: { //Negate the condition
$lt: 0
}
}
}
}
})
通过这种方式,您可以找到符合给定条件的所有匹配文档。
db.collection.find({
detail: {
$not: {
"$elemMatch": {
price: {
$gt: 3
}
}
}
}
})
你可以使用聚合来做到这一点。
db.orders.aggregate([
{
$unwind:"$detail"
},
{
$match:{
"detail.price":{$gt:0}
}
}
]);
考虑 mongodb 中的数据:
{
"ordernumber" : "161288",
"detail" : [
{
"articlenumber" : "1619",
"price" : 10,
},
{
"articlenumber" : "1620",
"price" : 0,
}
]
}
基本订单数据,其中包含一系列文章。
现在我想查询所有订单,其中所有商品的详细价格都> 0。因此未选择上面的订单,因为 1 件商品的价格为零。
这个错误($all 需要一个数组):
db.orders.find({'detail.price': { $all: { $gt: 0 }}})
如果至少有一个价格 > 0,这会找到所有订单。
db.orders.find({'detail.price': { $gt: 0 }})
这怎么可能? Select 只有数组中的所有项目都符合条件的文档?
db.collection.find({
detail: {
$not: {
"$elemMatch": {
price: { //Negate the condition
$lt: 0
}
}
}
}
})
通过这种方式,您可以找到符合给定条件的所有匹配文档。
db.collection.find({
detail: {
$not: {
"$elemMatch": {
price: {
$gt: 3
}
}
}
}
})
你可以使用聚合来做到这一点。
db.orders.aggregate([
{
$unwind:"$detail"
},
{
$match:{
"detail.price":{$gt:0}
}
}
]);