【发布时间】:2019-12-11 22:38:21
【问题描述】:
我正在使用 Node 和 MongoDB 作为 api。我正在尝试从数据库中获取根据设备 ID(工作得很好)以及时间戳整数过滤的结果。用户可以选择设置开始时间、结束时间,或者两者都设置,或者都不设置。所有数据似乎都正确发送,但结果很奇怪,看起来不合逻辑,所以我显然做错了什么。
这是对数据库的调用:
exports.findByDeviceId = (id, start, end, cb) => {
// start and end times provided
if (start !== undefined && end !== undefined) {
let query = db.entries.find({
$and: [
{device_id: id},
{timestamp: {$gte: start}},
{timestamp: {$lte: end}}
]
}).sort({index: 1})
console.log('start and end')
query.toArray((err, myEntries) => {
if (err) return cb(err, null)
else {
return cb(null, myEntries)
}
})
// only start time provided
} else if (start !== undefined && end === undefined) {
let query = db.entries.find({
$and: [
{device_id: id},
{timestamp: {$gte: start}}
]
}).sort({index: 1})
console.log('only start')
query.toArray((err, myEntries) => {
if (err) return cb(err, null)
else {
return cb(null, myEntries)
}
})
// only end time provided
} else if (start === undefined && end !== undefined) {
let query = db.entries.find({
$and: [
{device_id: id},
{timestamp: {$lte: end}}
]
}).sort({index: 1})
console.log('only end')
query.toArray((err, myEntries) => {
if (err) return cb(err, null)
else {
return cb(null, myEntries)
}
})
// no time constraints provided WORKS CORRECTLY
} else {
db.entries.find({device_id: id}).sort({index: 1}).toArray((err, myEntries) => {
console.log('no start, no end')
if (err) return cb(err, null)
else {
return cb(null, myEntries)
}
})
}
}
为了对此进行测试,我有两个条目,一个时间戳为 500,第二个时间戳为 10000。以下是我得到的一些奇怪结果:
?start=0 Both entries show up; as expected
?start=200 Only the entry with timestamp of 500 gets returned; both are expected
?start=700 Neither is returned; entry with timestamp 10000 is expected
?end=0 Neither entry is returned; as expected
?end=501 Both are returned; only entry with timestamp 500 is expected
?end=499 Only entry with 10000 is returned; Neither are expected
我还没有测试过同时指示开始和结束时会发生什么。
如果重要的话,在数据库中,时间戳字段是一个 Int32 字段。
知道我做错了什么吗?似乎问题出在我对 $gte 和 $lte 的使用上。 Here 是那些文档。它们看起来很简单。
感谢任何帮助。
编辑:这是一个示例条目:
{"_id":"xyz","index":1,"serial":"123","spent_c":0,"temp_c":2354,"direction":0,"battery":98,"timestamp":1519773832,"rh_c_1":0,"rh_c_2":0,"tp_c_1":2354,"tp_c_2":2374,"remain_c":10000,"device_id":"abc"}
【问题讨论】:
-
您的架构是什么样的?您能否举一个运行这些查询时正在查看的数据的示例?
-
我添加了一个示例条目。如果您需要更多信息,请告诉我。