最近特定日期的 Firestore 查询 |扑动



我有一些文档包含用FieldValue.serverTimestamp()设置的时间戳,我想根据过去 5、10 或 30 天查询文档。

这可以通过使用Firestore查询来实现吗,我是否必须在客户端上提取所有数据并进行过滤?

现在我得到这样的文件:

QuerySnapshot qShot = await _db
.collection('content')
.document(userID)
.collection('favorites')
.orderBy('timestamp', descending: true)
.getDocuments().catchError((onError){print(onError);});

编辑(添加 .where('timestamp', isGreaterThan: '5DAYSOLD_TIMESTAMP'((;

结果为颤振:文档 []

编辑

FieldValue.serverTimestamp()生成的时间戳如下所示May 12, 2020 at 2:46:46 PM UTC+3

你可以试试这个, 由于 Firestore 从纪元中保存时间戳(以毫秒为单位(,因此您可以在前端生成 5 天前的时间戳并查询数据库。

int x = DateTime.now().subtract(Duration(days:5)).toUtc().millisecondsSinceEpoch;

现在,您可以修改查询以显示时间戳大于 x 的所有结果。

因此,您的代码将更新为

QuerySnapshot qShot = await _db
.collection('content')
.document(userID)
.collection('favorites')
.where('timestamp',isGreaterThan:x)
.orderBy('timestamp', descending: true)
.getDocuments().catchError((onError){print(onError);});

希望这有帮助!

您必须像这样使用时间戳进行查询

DateTime currentDate= DateTime.now();
DateTime queryDate= currentDate.substract(Duration(days:5));
Timestamp  timestamp= Timestamp.fromDate(queryDate);

QuerySnapshot qShot = await _db
.collection('content')
.document(userID)
.collection('favorites').
.where('timestamp',isGreaterThanOrEqualTo:timestamp)
.orderBy('timestamp', descending: true)
.getDocuments().catchError((onError){print(onError);});

我认为您可以尝试在查询中添加一个where句子。喜欢这个:

QuerySnapshot qShot = await _db
.collection('content')
.document(userID)
.collection('favorites')
.where('timestamp',isGreaterThan:'5DAYSOLD_TIMESTAMP')
.orderBy('timestamp', descending: true)
.getDocuments().catchError((onError){print(onError);});

另外,你可以这样做

//Datetime
DateTime daysAgo= date.subtract(const Duration(days: 30));
//Apply to your firestore query
.where("date", isGreaterThanOrEqualTo: daysAgo)
.orderBy('date', descending: true)

最新更新