2016-08-03 61 views
2

我是很新的NoSQL和奋力写这个查询 我对Node.js的查找基于集团的猫鼬

我想实现的是用猫鼬得到一个最新的结果最新记录基于集团的设备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

注:beginDayID,endDayID是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); 
    }) 
+0

请参阅我的答案 - 如果它不适用于您,请显示一些真实的示例文档和预期输出,以便我们可以更具体 – DAXaholic

回答

2

我假设你有文件有点类似于此

/* 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 
    } 
} 
输出文件形外观

注意th在$sort的附加阶段,因为在谈论保持'最后的值'时你必须指定一个顺序。您可能需要指定另一个排序,如果您有其他要求

+0

按预期工作,感谢您的帮帮我 – XPLOT1ON