【问题标题】:How to order items in alphabetical order in firebase cloud firestore android [closed]如何在firebase cloud firestore android中按字母顺序排序项目[关闭]
【发布时间】:2021-06-24 01:42:51
【问题描述】:

我有一个名为 name in name 的集合,它有一些随机名称。我想按字母顺序显示名称。

谢谢

【问题讨论】:

  • 您尝试过什么了吗?如果没有,关于订购数据的文档是一个很好的起点:firebase.google.com/docs/firestore/query-data/order-limit-data
  • 是的,我试过 cityRef.orderBy("name", Query.Direction.DESCENDING)。但这对我不起作用。感谢您评论我的问题
  • 按升序排列名称的任何其他方式
  • 记录的方式应该可以工作。如果您无法让它为您工作,请将您的问题编辑到show what you tried and where you got stuck。我强烈建议研究该链接,因为遵循其中的指导可以最大限度地提高有人提供帮助的机会。

标签: android firebase kotlin google-cloud-firestore


【解决方案1】:

我相信您将文档 ID 称为“名称”是在混淆术语。

如果您的数据如下所示:

{
  "names": {                               // Collection
    "Tom": { age: 42, country: "US" },     // Document
    "sally": { age: 38, country: "AU" },   // Document
    "richard": { age: 36, country: "UK" }, // Document
    /* ... */
  }
}

"tom""richard""sally" 是文档 ID,而不是名称。要使用lexicographic 顺序(计算机和 Firestore 在二进制级别上理解的顺序)对这些“名称”进行排序,您可以使用:

val db = Firebase.firestore

db.collection("names")
  .orderBy(FieldPath.documentId())
  .get()
  .addOnSuccessListener { documents ->
    Log.d(TAG, "Found ${documents.size()} documents")
    for (document in documents) {
      Log.d(TAG, "> ${documents.getReference().getPath()}")
    }
  }
  .addOnFailureListener { exception ->
    Log.w(TAG, "Error getting documents: ", exception)
  }

上述查询将返回/names/Tom,然后是/names/richard,然后是/names/sally

这是因为字典顺序与字母顺序不同。

"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"  // lexicographic order
"AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"  // alphabetical order

由于 Firebase 要求查询一次通过索引,除非您的文档 ID 都遵循相同的大小写样式,否则您将获得与预期不同的结果。为了克服这个问题,在允许您对文档 ID 使用任何大小写的同时,您应该在文档数据中存储一个新字段,其中包含文档的小写 ID。

{
  "names": {                                                    // Collection
    "Tom": { age: 42, country: "US", sortName: "tom" },         // Document
    "sally": { age: 38, country: "AU", sortName: "sally" },     // Document
    "richard": { age: 36, country: "UK", sortName: "richard" }, // Document
    /* ... */
  }
}

使用上面的数据,下面的查询现在将返回/names/richard,然后是/names/sally,然后是/names/Tom

val db = Firebase.firestore

db.collection("names")
  .orderBy("sortName", Query.Direction.ASCENDING)
  .get()
  .addOnSuccessListener { documents ->
    Log.d(TAG, "Found ${documents.size()} documents")
    for (document in documents) {
      Log.d(TAG, "> ${documents.getReference().getPath()}")
    }
  }
  .addOnFailureListener { exception ->
    Log.w(TAG, "Error getting documents: ", exception)
  }

【讨论】:

  • 感谢 samthecodingman 抽出时间为我发布这个概念。我的问题在下面的链接中。
  • 我在等你的 kotlin 代码解释。非常感谢
  • @RSumanRadhakrishnan 我现在已将代码示例更新为 Kotlin。您应该将其他 cmets 编辑到您的问题中。
  • 谢谢伙计。这个对我有用。非常感谢
猜你喜欢
  • 2022-01-07
  • 2022-01-06
  • 1970-01-01
  • 2022-01-13
  • 2018-09-15
  • 2011-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多