我在 cloud firestore 中有一个集合,其中包含许多文档,这些文档具有创建文档时的时间戳值,以及更多信息。我正在经历一些非常奇怪的行为,我只是无法绕开我的头。
我想做的是:
- 根据时间戳值查找最新文档 查找更新于 1 小时前
- 、24 小时前和 7 天前的最早文档。
我有这些疑问:
var snapshotNow = await Firestore.instance
.collection(stationName)
.orderBy('servertime', descending: true)
.limit(1)
.snapshots()
.first;
并找到 1 小时前,依此类推:
var dateTime = DateTime.now().subtract(duration);
要检索 1 小时前的文档:
var snapshotThen = await Firestore.instance
.collection(stationName)
.where('servertime', isGreaterThan: dateTime)
.orderBy('servertime', descending: false)
.limit(1)
.snapshots()
.first;
出于某种原因,这两个非常不同的查询每次都检索相同的文档。也就是说:我从两个查询中获取集合中的最新文档。
我试图做几件事来找出问题所在:
1(不查看日期,通过删除查询中的.where
。这应该使snapshotThen
成为集合中最古老的文档。我实际收到的是馆藏中的最新文件。这意味着在升序和降序排序时,返回的文档与第一个文档相同。
2( 将限制增加到 1 个以上的文档。将限制从limit(1)
增加到limit(10)
时。对于升序排序,这将始终返回最新的 10 个文档(如预期的那样(。对于订单通过下降,奇怪的事情发生了。我希望它返回集合中最古老的 10 个文档。它返回的是两件事之一;1( 10 个最新文档,从最旧到最新排序,或 2( 仅最新文档(不是 10 个文档的列表,而是仅包含 1 个文档的列表(。
非常感谢任何帮助,我已经为此工作了很长时间,我只是无法弄清楚问题出在哪里。我发现最令人沮丧的是行为发生了变化;有时我只得到 1 个文档,有时我得到 10 个文档,所有这些都具有相同的查询。
在我看来,问题在于 Firestore 时间戳的格式。
Firestore 时间戳示例如下:
Timestamp { _seconds: 1575888466, _nanoseconds: 725000000 }
我已经复制了您所描述的内容,并且使用Firestore.Timestamp
运行良好
您可以使用Firestore.Timestamp.now()
以 Firestore 时间戳格式获取当前时间,并Firestore.Timestamp.fromMillis(Date.now()-[MS])
,其中 [MS] 是要减去的时间(以毫秒为单位(。
1 小时 = 3600000 ms
1 天 = 86400000 ms
所以一个例子如下:(我正在使用 Node.js(
let postsRef = db.collection('dates');
const hour= 3600000;
const fullday= 86400000;
var firenow = Firestore.Timestamp.now()
var firepast = Firestore.Timestamp.fromMillis(Date.now()-fullday);
var range1 = postsRef.where("time", ">=", firepast).where("time", "<=", firenow);
let query1 = range1.get()
.then(snapshot => {
if (snapshot.empty) {
console.log('No matching documents.');
return;
}
snapshot.forEach(doc => {
console.log(doc.id, '=>', doc.data());
});
})
.catch(err => {
console.log('Error getting documents', err);
});
上面将为您提供带有过去一小时时间戳的文档,将hour
替换为fullday
将为您提供最后 24 小时。