Reputation: 1736
I'm trying to use query for Firestore on iOS (Swift):
db.collection(FS_PICS)
//.whereField("category", arrayContains: "Animals")
.whereField("category", arrayContains: ["Animals", "Dogs"])
.getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
print("\(document.documentID) => \(document.data())")
}
}
}
It doesn't return any result with
// doesn't work
.whereField("category", arrayContains: ["Animals", "Dogs"])
or with
// doesn't work
.whereField("category", in: ["Animals", "Dogs"])
but I have 8 result for:
// It works!!
.whereField("category", arrayContains: "Animals")
It doesn't work like OR even like AND, because it is also does't work:
// It works!!
.whereField("category", arrayContains: ["Animals"])
So what is the idea of this function, what should I do to get OR ?
Upvotes: 3
Views: 2362
Reputation: 1736
The problem is in the example of the code in the documentation. It should be arrayContainsAny
It is correct for other languages:
Upvotes: 3
Reputation: 12385
EDIT: Based on the screenshot, the documentation is incorrect, you're right. Some clarifications, regardless:
This is wrong:
.whereField("category", arrayContains: ["Animals", "Dogs"])
arrayContains
must input a singular type of what that array contains (i.e. a string array inputs a string), not a collection. arrayContains
does not perform OR or AND operations, it only performs equals of a single instance of an element inside an array.
This is correct:
.whereField("category", arrayContains: "Dogs")
This is also correct:
.whereField("category", arrayContainsAny: ["Animals", "Dogs"])
The arrayContainsAny
query performs an OR operation where category
must contain "Animals" or "Dogs".
And for measure, there is also in
which performs an OR operation on a non-collection (i.e. non-array) field. If the "category" field were just a String
(and not an Array
), you could perform an OR query with:
.whereField("category", in: ["Animals", "Dogs"])
Upvotes: 3