我对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
注意: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 :(得分:3)
我假设您的文档与此类似
/* 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
的附加阶段,因为您在谈论保留“最后的值”时必须指定一个订单。如果您有其他要求,则可能必须指定其他排序