我在 cloud firestore 中有一个集合,其中包含许多文档,这些文档具有文档创建时间的时间戳值,以及更多信息。我正在经历一些非常奇怪的行为,我无法理解。
我想要做的是:
我有这些疑问:
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 个文档(如预期)。对于 orderBy 降序,发生了一些奇怪的事情。我希望它从集合中返回最旧的 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 毫秒
1 天 = 86400000 毫秒
所以一个例子如下:(我正在使用 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 小时。
关于firebase - Flutter Cloud Firestore orderBy 和 limit 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59204580/