【问题标题】:Query a collecion with n number of records查询具有 n 条记录的集合
【发布时间】:2020-03-14 18:40:43
【问题描述】:
  • 我有一个名为 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 它查找整个数据而不是最后更新的数据。 请问我该怎么做?谢谢

【问题讨论】:

    标签: mongodb mongoose mongodb-query


    【解决方案1】:

    我猜你需要 aggregation ,试试类似的东西。我在这里所做的是首先使用locationDate按升序($sort:1)对数据进行排序(我猜它是设备的最后一个位置时间戳),然后按现场device 应用分组,然后选择管道中的最后一个数据。你也可以做$sort:-1(降序排序并选择$first

    $last 是做什么的?

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

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

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

    【讨论】:

      猜你喜欢
      • 2010-09-23
      • 1970-01-01
      • 2013-07-18
      • 2021-03-27
      • 2021-05-07
      • 2013-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多