What would be the right way to query a field that is an array of maps.
Currently the structure is
Collection1
Document1
-papers: <---- This is an array
(0):
-Name:abc
-Id:123
(1):
-Name:xyz
-Id:456
And this is my code
DocumentReference docRef = db.collection("Collection1").document("Document1");
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document != null && document.exists()) {
//?? how can I retrieve papers
}
}
});
Basically do I retrieve it and cast it as an ArrayList> and then loop through it to create my final ArrayList ?
Or how does it work ?
When it comes to the official documentation regarding how to update elements in an array in Firestore, it says that: If your document contains an array field, you can use arrayUnion() and arrayRemove() to add and remove elements. arrayUnion() adds elements to an array but only elements not already present.
Firestore lets you write a variety of data types inside a document, including strings, booleans, numbers, dates, null, and nested arrays and objects.
js admin clients have listCollections() on Firestore to get that list. Or, if you're looking for subcollections nested under a document, use DocumentReference. listCollections(). If you want to get a list on any platform, you should maintain that list yourself in a known collection inside a known document id.
With the in query, you can query a specific field for multiple values (up to 10) in a single query. You do this by passing a list containing all the values you want to search for, and Cloud Firestore will match any document whose field equals one of those values.
As per official documentation regarding arrays:
Although Cloud Firestore can store arrays,
it does not support
querying array members or updating single array elements.
If you only want to get the entire papers
array you need to iterate over a Map
like this:
Map<String, Object> map = document.getData();
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getKey().equals("papers")) {
Log.d("TAG", entry.getValue().toString());
}
}
But note, even if papers
object is stored in the database as an array, entry.getValue()
returns an ArrayList
, not an array
.
Edit 13 Aug 2018:
According to the updated documentation regarding array membership, now it is possible to filter data based on array values using whereArrayContains()
method. A simple example would be:
CollectionReference citiesRef = db.collection("cities");
citiesRef.whereArrayContains("regions", "west_coast");
This query returns every city document where the regions field is an array that contains west_coast. If the array has multiple instances of the value you query on, the document is included in the results only once.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With