0

I have data in Firestore like this:

enter image description here

And I want to query it from Java to get all orders where any item status would be equal to TEST. Is it possible?

It works fine when I get all orders from client like:

CollectionReference ordersRef = dbFirestore.collection("orders");    
Query query = ordersRef.whereEqualTo("client", "client1");

But I couldn't do it as I need. I try this

CollectionReference ordersRef = dbFirestore.collection("orders");    
Query query = ordersRef.whereEqualTo("items.status", "TEST");

but it returns an empty array


UPDATE AFTER ALEX'S ANSWER


If I convert items in a Map like: then this query works fine

Query query = ordersRef.whereEqualTo("orders.items.status", "TEST");

but this doesn´t resolve the problem because the items Map need to have several objects like enter image description here

--

Asenjo
  • 109
  • 4
  • 11

1 Answers1

2

And I want to query it from Java to get all orders where any item status would be equal to TEST. Is it possible?

That's currently not possible. You cannot query a collection based on a value that exists within objects that exist in an array field. You could however query using an entire object and call Query#whereArrayContains(). So instead of trying to query based only on the value of status you have queried based on an object that contains all three fields. Besides that, the following query would have worked:

Query query = ordersRef.whereEqualTo("client.items.status", "TEST");

If that data would have been added as a map (object) and not as an array.

However, to solve such a problem you should consider creating a sub-collection called items inside each document. In this way, a query like this should do the trick:

Query queryByStatus = dbFirestore.collectionGroup("orders").whereEqualTo("status", "TEST");

When using such a query, please also don't forget to create an index.

Why would you use this solution? Simply because there are no limitations. When you store lots of objects inside an array, you might hit the maximum limit of 1 Mib per document.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • hi Alex, I dont understand the sub-collection approach. Should I create a new collection called items and reference it inside orders.items? – Asenjo Jul 11 '23 at 10:31
  • By sub-collection I mean, instead of adding those items separately inside the array, get the array out of the document and add the exact item as a separate document in a sub-collection that belongs to the document. Is it clear now? – Alex Mamo Jul 11 '23 at 10:55