MongoDB - 从startDate获取数据到endDate

时间:2016-08-01 07:36:16

标签: javascript mongodb mongodb-query

所以,我在DB中有这样的JSON(我使用mongoDB)

{ 
    "uSN": "100030001",
    "timestamp": 1470009600,
    "timetag": 1082016,
    "monthtag": 82016,
    "hourtag": 11,
    "mintag": 10,
    "yeartag": 2016, 
    "id": "d100030001_01082016_11_10"
  },
  { 
    "uSN": "100030001",
    "timestamp": 1470096000,
    "timetag": 2082016,
    "monthtag": 82016,
    "hourtag": 11,
    "mintag": 10,
    "yeartag": 2016, 
    "id": "d100030001_02082016_11_10"
  },
  { 
    "uSN": "100030001",
    "timestamp": 1469850900,
    "timetag": 30072016,
    "monthtag": 72016,
    "hourtag": 10,
    "mintag": 55,
    "yeartag": 2016, 
    "id": "d100030001_30072016_10_55"
  },
  { 
    "uSN": "100030001",
    "timestamp": 1469923200,
    "timetag": 31072016,
    "monthtag": 72016,
    "hourtag": 11,
    "mintag": 10,
    "yeartag": 2016, 
    "id": "d100030001_31072016_11_10"
  },
  { 
    "uSN": "100030001",
    "timestamp": 1469577600,
    "timetag": 27072016,
    "monthtag": 72016,
    "hourtag": 11,
    "mintag": 10,
    "yeartag": 2016, 
    "id": "d100030001_27072016_11_10"
  }

我正在尝试从我的mongo shell进行查询以获取数据从2016年7月30日到2016年8月1日。

我正在使用这个:
db.dataProfTable.find({ uSN: '100030001', timestamp : {'$gte': new Date(1469836800), '$lte': new Date(1470009600)})
db.dataProfTable.find({'uSN': '100030001', 'timetag': {$gte: '30072016', $lt: '01082016'}})

但它不起作用。我该如何解决这个问题?

3 个答案:

答案 0 :(得分:3)

将输入作为日期范围" 30-07-2016"到" 01-08-2016",构建一些在您的查询中使用的JS日期。以秒为单位获取时间戳(如文档架构所示),除以1000:

var start = new Date("2016-07-30")/1000,
    end = new Date("2016-08-01")/1000;
db.dataProfTable.find({
    "timestamp": { "$gte": start, "$lte": end }
})

示例输出

/* 1 */
{
    "_id" : ObjectId("579f04ccd8f31a5788eba0fb"),
    "uSN" : "100030001",
    "timestamp" : 1470009600,
    "timetag" : 1082016,
    "monthtag" : 82016,
    "hourtag" : 11,
    "mintag" : 10,
    "yeartag" : 2016,
    "id" : "d100030001_01082016_11_10"
}

/* 2 */
{
    "_id" : ObjectId("579f04ccd8f31a5788eba0fd"),
    "uSN" : "100030001",
    "timestamp" : 1469850900,
    "timetag" : 30072016,
    "monthtag" : 72016,
    "hourtag" : 10,
    "mintag" : 55,
    "yeartag" : 2016,
    "id" : "d100030001_30072016_10_55"
}

答案 1 :(得分:2)

     Try This !!!

有关,

1. Monthtag

  

db.dataProfTable.find({uSN:'100030001',$和:[{monthtag:{$ gte:   72016}},{monthtag:{$ lte:82016}}]})

2. 时间戳

  

db.dataProfTable.find({uSN:'100030001',$和:[{timestamp:{$ gte:   1469836800}},{timestamp:{$ lte:1470009600}}]})

答案 2 :(得分:1)

按下面的时间戳使用查询:

var start = new Date("07/30/2016").getTime()/1000 //Date Format:mm/dd/yyyy. Doing by 1000 since u stored in seconds
var end = new Date("08/01/2016").getTime()/1000
db.dataProfTable.find({ uSN: '100030001', $and:[ {timestamp : {$gte:start}},{timestamp : {$lte: end}}]})

通过以下时间标签查询:

db.dataProfTable.find({'uSN': '100030001', 'timetag': {$gte: 30072016, $lt: 01082016}}) // Since u stored as number for timetag