【问题标题】:Mongo Aggregation for inventory stock data库存数据的 Mongo 聚合
【发布时间】:2021-01-20 03:55:01
【问题描述】:

我有以下架构。

{
    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 个产品? 对此有什么想法吗?

【问题讨论】:

  • { $match: { "available_in.stock": {$lt: 10 } } },你试过吗?你能分享你尝试过的sn-p代码吗?
  • 谢谢,但是,正如我提到的,available_in 是一个包含多个对象的数组。所以我不能使用上面的代码。 @Tahero
  • 尝试放松 available_in 然后 { $match: { "available_in.stock": {$lt: 10 } } }

标签: javascript node.js mongodb mongoose aggregation-framework


【解决方案1】:

试试这个:

db.collection.find({"availabe_in.stock" : {$lt : 10}})

或使用聚合管道:

db.collection.aggregate([{
     $match :{
          "availabe_in.stock" : {$lt : 10}
     }
}])

注意:0也小于10,所以你不需要任何特殊的or查询来添加equals to 0条件

如果您只想获取 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"}
    }
}])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-27
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多