Yura Buyaroff
Yura Buyaroff

Reputation: 1736

Firestore "array-contains-any" not working

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

Answers (2)

Yura Buyaroff
Yura Buyaroff

Reputation: 1736

The problem is in the example of the code in the documentation. It should be arrayContainsAny enter image description here

It is correct for other languages:

enter image description here

Upvotes: 3

slushy
slushy

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

Related Questions