Mongoid:使用group by,distinct和count操作进行查询

ali*_*him 2 mongodb mongoid

假设我有名称的模型ItemAvailability是有product_id,vendor_id,shop_id

我想GROUP_BY上product_id,并选择那些product_id已经distinct(vendor_id)有计数> = 3.

使用MongoID这是可行的吗?

样本数据:

ItemAvailability
product_id vendor_id shop_id
1              1        1
1              1        2
1              1        3
2              2        1
2              2        2
1              2        1
1              2        2
1              2        3
1              3        1
1              3        2
Run Code Online (Sandbox Code Playgroud)

在上面的数据集中,结果应该是1,因为它在所有供应商1,2和3中都可用.

2不应该是结果,因为它只由供应商2提供.

如果需要更多细节,请告诉我?

Ana*_*lan 6

你可以用aggregation frameworkgroup by查询在MongoDB中.看一下docs介绍.它非常强大,您可以通过查看示例来了解它.

对于您所描述的方案,以下查询应该有所帮助:

db.ItemAvailability.aggregate(
    [
        // Group By product_id, vendor_id
        {
            "$group": { _id: { product_id: "$product_id", vendor_id: "$vendor_id" } }
        },
        // Group results from above step by product_id and get the count
        {
            "$group": { _id: "$_id.product_id", count: { "$sum": 1 } }
        },
        // Filter the records for count >= 3
        {
            "$match": { count: { "$gte": 3 } }
        }
    ]
)
Run Code Online (Sandbox Code Playgroud)