在 mongodb 中使用 group by 子句获取值的范围

Get range of values with group by clause in mongodb

我在 mongodb.

中有一个这样的 collection
{
  "_id": "1235677",
  "name" : "xyz",
  "time" : ISODate(2015-07-20T09:00:00Z)
},
{
  "_id": "1235677",
  "name" : "xyz",
  "time" : ISODate(2015-07-20T11:00:00Z)
},
{
  "_id": "1235677",
  "name" : "abs",
  "time" : ISODate(2015-07-20T11:00:00Z)
}

如何获得数据库中所有名称的 Max(time) 减去 Min(time)。相当于此 sql 查询 -

SELECT name, Max(time)-Min(time) from tablename group by name

您将 aggregation framework 用于 MongoDB,如下所示:

db.collection.aggregate([
    { "$group": {
        "_id": "$name",
        "minTime": { "$min": "$time" },
        "maxTime": { "$max": "$time" }
    }},
    { "$project": {
        "duration": { "$subtract": [ "$minTime", "$maxTime" ] }
    }}
])

您对不涉及基本(SQL 等效)语句类型的所有内容(最佳)使用聚合框架:

SELECT something FROM table

这里的操作如下:

  • $group: Is the same as "GROUP BY", where you specify the "key(s)" you want want to aggregate for within the _id primary key value. The $min and $max 运算符分别与 "MIN()" 和 "MAX()" 相同,因为它作为 "grouping" 的函数作为 "accumulators".

  • $project 是 MongoDB 术语中一般语法的扩展。这允许您 "manipulate" 现有字段值(在这种情况下从 $group 计算到文档中的新值。

    所以在这里 "calculation" 由 $subtract 从两个值中应用以确定结果。

虽然并不总是给出具体示例,但我强烈建议您完整地查看 SQL to MongoDB mapping Chart section of the core documentation. As well as looking though and learning the aggregation operators 本身。

请尝试以下操作:

 db.collection.aggregate([
  { $group:{_id:"$name",maxt: {$max:"$time"}, mint : {$min:"$time"}} },
  { $project: {"_id" : 0 ,"name": "$_id", 
    "time" : {$subtract: ["$mint","$maxt"]}} }
 ]);