我有一个下面的方案。
{
name: {
type: String
},
available_in: [{
variation: {
type: Number
},
variation_type: {
type: String,
enum: ['gm', 'kg', 'ml', 'ltr', 'unit', 'lbs', 'oz', 'pound', 'gallon']
},
rate: {
type: Number
},
stock: {
type: Number
},
discount_type: {
type: String,
enum: ['special', 'daily', 'normal', '', ' ']
},
discount_percentage: {
type: Number
},
start_date: {
type: Date
},
end_date: {
type: Date
},
discounted_rate: {
type: Number,
required: true
},
is_deleted: {
type: Boolean,
default: false
},
tax_percentage: {
type: Number,
default: 0
},
tax_value: {
type: Number,
default: 0
}
}],
}我想拿出available_in库存小于10且等于0的产品。我试着将查询放在$match中,但似乎不起作用。例如:-我有5个产品,其中2个产品在available_in数组中有一个对象,其中的库存小于10或0,那么如何通过mongo聚合获取这2个产品?对此有什么想法吗?
发布于 2020-10-05 17:55:34
试试这个:
db.collection.find({"availabe_in.stock" : {$lt : 10}})或者使用聚合管道:
db.collection.aggregate([{
$match :{
"availabe_in.stock" : {$lt : 10}
}
}])注意:0也小于10,因此添加equals to 0条件不需要任何特殊的or查询
如果您只想获取available_in数组中匹配元素,那么可以使用下面的聚合管道:
db.collection.aggregate([{
$unwind : "$available_in"
},{
$match : {
"available_in.stock" : {
$lt : 10
}
}
},{
$group : {
_id : "$_id",
name : {$first : "$name"},
available_in : {$push : "$available_in"}
}
}])https://stackoverflow.com/questions/64205979
复制相似问题