I, naturally, used queries a lot in the days of MySQL / MariaDB on my web databases, so Lesson 11 from Module 1 of the CWC+ iOS Database course was always going to be one that I looked forward to.
Google has ensured that querying databases is pretty much as straightforwards as adding / editing / deleting entries.
This will return only those entries where the field field-name
matches any of the terms in the in:[]
array:
let db = Firestore.firestore()
let myCollection = db.collection("collection-name")
let myQuery = myCollection.whereField("field-name", in: ["search-term-1", "search-term-2"])
myQuery.getDocuments { querySnapshot, error in
for doc in querySnapshot!.documents {
print(doc.data())
}
}
We can use the following query to return entries that do not match the terms in the array:
let myQuery = whereField("field-name", notIn: ["search-term-1", "search-term-2"])
The following code will return entries in an array that matches ‘1’:
let myQuery = whereField("array", arrayContains: 1)
And the following will return entries in an array that matches any entry in the second array:
let myQuery = whereField("array", arrayContainsAny: [1,2,3])
As before, the above code is for reference, and should really be used together with error handling because we’re force unwrapping and we should check for nil
.