查询Firestore中子集合中的最大值

huangapple go评论78阅读模式
英文:

query for max values among subcollections in firestore

问题

我想在我的应用程序中添加排行榜,其中会显示排名前50名的用户。

我的Firestore数据库结构如下:

用户(集合) -> 用户UID(文档) -> 用户数据(集合) -> 用户UID(文档) -> 字段

其中一个字段名为rank。

现在,我想执行类似这样的操作:

db
    .collection("USERS")
    .document(UID)
    .collection("UserData")
    .document(UID)
    .orderBy("rank", Query.Direction.DESCENDING)
    .limit(50)
    .get()

但我知道这不起作用,因为它将查询特定文档,而不是整个USERS集合。

有没有办法在不进入每个文档并获取该值的情况下查找每个用户的排名?还是我必须更改数据库的结构?

谢谢

英文:

I would like to add Leaderboard to my app in which it will show the 50 top-ranked users.

My firestore is built as follows:

USERS (collections) -> UID (document) -> UserData (collection) -> UID (document) -> fields

one of the fields is called rank.

Now, I had like to perform something like that:

db
    .collection( "USERS" )
    .document(UID)
    .collection("UserData")
    .document(UID)
    .orderBy( "rank", Query.Direction.DESCENDING )
    .limit( 50)
    .get()

But I know it is not going to work since it will query the specific document and not the whole collection of USERS.

Is there any way to search what is the rank of each user without going into each document and get that value? Or do I have to change the structure of the database?

Thank you

答案1

得分: 1

如果您想在所有具有相同名称的子集合之间查询文档,您可以执行collection group查询,您可以使用该查询来查找和对所有这些子集合中的文档进行排序。

db
    .collectionGroup("UserData")
    .orderBy("rank", Query.Direction.DESCENDING)
    .limit(50)
    .get()
英文:

If you want to query documents among all subcollections of the same name, you would want to do a collection group query, which you can use to find and sort all documents within those subcollections.

db
    .collectionGroup("UserData")
    .orderBy( "rank", Query.Direction.DESCENDING )
    .limit( 50)
    .get()

huangapple
  • 本文由 发表于 2020年10月25日 04:36:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/64517771.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定