查询具有n条记录的集合

时间:2019-11-19 09:34:23

标签: mongodb mongoose mongodb-query

  • 我每秒有一个名为GPS的集合,与服务器连接的n个设备会将数据推送到集合。 样本数据
 {
     "_id" : ObjectId("5dd2d4f7d092fb70c022c700"),
     "date" : "2019-11-18",
     "altitude" : "0.0",
     "latdegree" : "N",
     "gpspositioning" : "V",
     "positionType" : "GPS",
     "latitude" : "12.900660",
     "range" : null,
     "gsmsignalstrength" : "46",
     "battery" : "87",
     "terminalstatus" : "00000000",
     "longitude" : "80.2347400",
     "satellites" : "0",
     "created" : "2019-11-18 17:29:26.991Z",
     "longdegree" : "E",
     "tumblingtimes" : "0",
     "positionaccuracy" : "52",
     "time" : "17:30:01.000Z",
     "locationDate" : "2019-11-18 17:30:01.000Z",
     "device" : "6005868660"
 }

所以现在我想用每个设备的最新更新值(例如,以数组为单位的设备个数)查询此集合。例如

[
  {
    device:1,
    lat:11,
    long:4111
  },
  {
    device:2,
    lat:11,
    long:4111
  },
  {
    device:3,
    lat:11,
    long:4111
  }
.....n]

我尝试使用find和$ natural来查找整个数据,而不是最近更新的数据。 我该怎么做?谢谢

1 个答案:

答案 0 :(得分:0)

我猜您需要aggregation,尝试类似的方法。我在这里要做的是先按locationDate的升序对数据进行排序($sort:1)(我猜它是设备的最后一个位置时间戳),然后按现场应用分组{ {1}},然后选择管道中的最后一个数据。您还可以执行device(降序排序并选择$sort:-1

$last的作用是什么?

  

返回将表达式应用于最后一个值的结果   一组文档中的文档,这些文档按字段共享同一组。   仅在文档按定义的顺序显示时才有意义。

$first

OR

 db.gps.aggregate(
       [
         { $sort: { locationDate: -1 } },
         {
           $group:
             {
               _id: "$device",
               latitude:{$first: "$latitude"},
               longitude: {$first: "$longitude"},
               lastupdateValue: { $first: "$locationDate" }
             }
         }
       ]
    )