【问题标题】:Find latest record based on Group Mongoose查找基于 Group Mongoose 的最新记录
【发布时间】:2016-12-09 12:59:38
【问题描述】:

我对 NoSQL 很陌生,并且很难编写此查询 我在 Node.js 上使用 Mongoose

我想要实现的是根据设备 ID 组获得一个最新结果。我用 SQL 写这个没有问题,但在 NoSQL 中很难做到。

这是模型设置

_id     DeviceID     Coordinate:{lat, long}
1       2            lat: 1, long: 2
2       3            lat: 2, long: 3
3       1            lat: 3, long: 3
4       3            lat: 5, long: 4
5       2            lat: 7, long: 5
6       2            lat: 9, long: 6
7       3            lat: 111, long: 7
8       2            lat: 113, long: 8

我想要的输出是:

_id     DeviceID     Coordinate:{lat, long}
3       1            lat: 3, long: 3
7       3            lat: 111, long: 7
8       2            lat: 113, long: 8

这是我尝试过的,但我得到的结果是undefined

注意:beginDayIDendDayID是mongoose的变量,ObjectId代表一天的开始和结束的_id。

mongoose.model('GPSData').aggregate([
  {$match: {_id:{$gte: beginDayID, $lt: endDayID}}},
  {$unwind: "$Coordinates"},
  {$project: {DeviceID: '$DeviceID' }},
  {$group: { DeviceID: '$DeviceID', $lat: '$Coordinates.lat', $long: '$Coordinates.long'}}

  ], (e, data) => {
     console.error(e)
     console.log(data)
     if (e) return callback(e, null);
     return callback(null, data);
   })

【问题讨论】:

  • 查看我的回答 - 如果它不适合您,请展示一些真实的示例文档和预期的输出,以便我们更具体

标签: javascript node.js mongodb mongoose


【解决方案1】:

我假设你有一些类似的文件

/* 1 */
{
    "_id" : 1,
    "DeviceID" : 1,
    "Coordinate" : {
        "lat" : 1,
        "long" : 2
    }
}

/* 2 */
{
    "_id" : 2,
    "DeviceID" : 2,
    "Coordinate" : {
        "lat" : 1,
        "long" : 6
    }
}
...

那么这样的聚合管道应该可以工作

mongoose.model('GPSData').aggregate([
  {
      $match: ... // your match filter criteria
  },
  {
      $sort: {
          _id: 1
      }
  },
  { 
      $group: { 
          _id: '$DeviceID',
          lastId: { $last: '$_id' },
          lat: { $last: '$Coordinate.lat' }, 
          long: { $last:'$Coordinate.long' }
      }
  },
  {
      $project: {
          _id: '$lastId',
          DeviceID: '$_id',
          lat: 1,
          long: 1
      }
  }
])

输出文件的形状是这样的

/* 1 */
{
    "_id" : 1,
    "DeviceID" : 1,
    "Coordinate" : {
        "lat" : 1,
        "long" : 2
    }
}

/* 2 */
{
    "_id" : 2,
    "DeviceID" : 2,
    "Coordinate" : {
        "lat" : 1,
        "long" : 6
    }
}

注意$sort 的附加阶段,因为在谈论保留“最后值”时必须指定顺序。如果您有其他要求,您可能需要指定其他排序方式

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    • 1970-01-01
    • 2012-11-11
    • 1970-01-01
    • 2021-07-20
    • 1970-01-01
    • 2021-07-17
    相关资源
    最近更新 更多