Reputation: 2564
Here is the schema for a test database:
I want to write a query that can get all the documents where contacts have id=1 in any of the array index.
I have checked array_contains
operator for Firestore, but my array has a map which then have field id.
Upvotes: 31
Views: 19170
Reputation: 19
If you have an array of maps or objects and want to get the docoments that contains this specific map/object like this,
you can use:
queryForCategory(categName: string, categAlias: string): Observable[] {
firestore.collection('<Collection name>', ref =>
ref.where('categories',
"array-contains", {
"alias": categAlias,
"title": categName
}
Upvotes: 1
Reputation: 1960
One solution is, as Doug said, to add an array with the data you need to query, and keep it up-to-date.
Another solution is to make contacts as a sub collection of the document, and_ then you could make queries of the contacts and get its parent.
final Query contacts = db.collectionGroup("contacts").whereEqualTo("id", 1);
for (DocumentSnapshot document : querySnapshot.get().getDocuments()) {
System.out.println(document.getId());
System.out.println(document.getString("parent_id"));
}
If you don't want to add the parent as another field, you can get it from the parent reference. Check this answer to Firestore - get the parent document of a subcollection.
snapshot.getRef().getParent().getParent().collection("people")
Upvotes: 1
Reputation: 317808
You currently can't build a query that looks for an object field within an array. The only things you can find in an array are the entire contents of an array element, not a part of an element.
With NoSQL type databases, the usual practice is to structure you data in a way that suits your queries. So, in your case, you're going to have to structure your data to let you find documents where an array item contains a certain string. So, you could create another array that contains just the strings you want to query for. You will have make sure to keep these arrays up to date.
You could also reconsider the use of an array here. Arrays are good for positional data, but unless these contacts need to be stored in a certain order, you might want to instead store an object whose keys are the id, and whose field data also contains the id and name.
Upvotes: 31
Reputation: 331
As Doug said, you can't query it, but, if you could structure your data to something that looks like this
id
as key and name
as valueid=1
db.collection("test").where("contacts.1", ">=", "").get()
Upvotes: 8