2017-01-04 71 views
0

的条件的我有一个MongoDB的存储来自不同传感器的数据。 它具有以下结构:查询的文档和它的所有的子文档匹配的mongodb

{ 
    "_id" : 1, 
    "sensorName" : "Heart Rate", 
    "samplePeriod" : 1000, 
    "data" : [ 
      { 
       "timestamp" : NumberLong("1483537204046"), 
       "dataPoints" : [ 68 70 ] 
      }, 
      { 
       "timestamp" : NumberLong("1483537206046"), 
       "dataPoints" : [ 68 70 ] 
      } 
    ] 
} 
{ 
    "_id" : 2, 
    "sensorName" : "Ambient Light", 
    "samplePeriod" : 500, 
    "data" : [ 
      { 
       "timestamp" : NumberLong("1483537204058"), 
       "dataPoints" : [ 56, 54, 54, 54 ] 
      }, 
      { 
       "timestamp" : NumberLong("1483537206058"), 
       "dataPoints" : [ 56, 54, 54, 54 ] 
      } 
    ] 
} 

现在比如我需要的“心率” - 文件将其所有字段和那些其“数据” - 子文档与条件匹配“时间戳1483537204000和1483537214000之间” 。

我知道的聚集,但无法弄清楚,如何不仅返回匹配的子文档,但回到整个“心率” - 文件仅包含在“数据”匹配的子文档。

我的结构是否有效?您是否有任何提示有效查询此类数据的更好结构?

在此先感谢!

回答

0

你可以尝试下面的东西。

$匹配,以保持心脏率纪录。

$过滤器来过滤该情况的子文档。

$项目中显示的结果。

aggregate([{ 
    $match: { 
     "_id": 1 
    } 
}, { 
    "$project": { 
     "_id": 1, 
     "sensorName": 1, 
     "samplePeriod": 1, 
     "data": { 
      "$filter": { 
       "input": "$data", 
       "as": "result", 
       "cond": { 
        $and: [{ 
         $gte: ["$$result.timestamp", 1483537204000] 
        }, { 
         $lte: ["$$result.timestamp", 1483537214000] 
        }] 
       } 
      } 
     } 
    } 
}]) 
+0

完美的作品!谢谢。 有没有办法在Java春天做到这一点? – Nas3nmann

相关问题