简体   繁体   English

Firestore通过字符串键查询文档

[英]Firestore Query documents by string key

I have a firestore db structure like so; 我有一个像这样的firestore db结构;

Imgur

How can i query all documents under auctions collection that have a given cargoOwnerId ? 如何查询auctions集合中具有给定cargoOwnerId所有文档?

I am using com.google.firebase:firebase-firestore:20.2.0 in my project. 我在项目中使用com.google.firebase:firebase-firestore:20.2.0

I have looked through similar issues here on stack overflow but no to success. 我在这里通过堆栈溢出看过类似的问题,但没有成功。

I have also read the documentation by Google about doing this here but nothing seems to work when I run the code below 我还阅读了Google的有关在此处执行此操作的文档,但是当我运行以下代码时,似乎没有任何效果

FirebaseFirestore.getInstance()
.collection("auctions")
.whereEqualTo("cargoOwnerId","ZkYu6H6ObiTrFSX5uqNb7lWU7KG3")
.get()
.addOnCompleteListener(task -> {

     Log.d("Logging", "Size: " + task.getResult().size());


});

I expect to return a list of all the documents that contain ZkYu6H6ObiTrFSX5uqNb7lWU7KG3 as the cargoOwnerId but it returns nothing at all. 我希望返回包含ZkYu6H6ObiTrFSX5uqNb7lWU7KG3作为cargoOwnerId的所有文档的列表,但它什么也不返回。 The size is 0. 大小为0。

Am i missing something? 我想念什么吗?

The way your document is structured, what you're trying to do is not possible. 文档的结构方式以及您要执行的操作都是不可能的。 You can't query by map properties when you don't also know the name of the map property. 当您不知道地图属性的名称时,也无法按地图属性查询。 The name of map property would also have to be consistent among all your documents. 在所有文档中,地图属性的名称也必须保持一致。

At the top level of your document, you apparently have a single field with the same id as the document, which is a map. 在文档的顶层,您显然具有与文档具有相同ID的单个字段,即地图。 It's not clear to me at all why you want a single map field in your document. 我根本不清楚,为什么要在文档中使用单个地图字段。 It seems to me that you don't want a single map and instead want all the fields of that map to be document fields instead. 在我看来,您不想要一个地图,而是希望该地图的所有字段都成为文档字段。 This would allow you to perform the query you're asking about. 这将允许您执行您要查询的查询。 Perhaps you made a mistake in populating the document. 也许您在填充文档时犯了一个错误。

This is possible. 这个有可能。

Try changing task.getResult().size() to just task.size() 尝试将task.getResult().size()更改为task.size()

Example: 例:

db.collection("auctions")
        .whereEqualTo("cargoOwnerId","ZkYu6H6ObiTrFSX5uqNb7lWU7KG3")
        .get()
        .addOnSuccessListener { documents ->

            Log.d("Logging", "Size: " + documents.size());


            for (document in documents) {
                Log.d(TAG, "${document.id} => ${document.data}")

            }
        }
        .addOnFailureListener { exception ->
            Log.w(TAG, "Error getting documents: ", exception)
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM