'Get contacts which have same phone number stored in phone number list in firestore
this is my first time trying Firestore. I have a collection named users
, where every user is a UID and every user has fields (name, phone, and contacts (array)). I want to get all users where any of the numbers stored in the user's contacts field exists in their phone field. I have tried to learn from documentation but that's too advanced for me right now.
I am using Kotlin and Jetpack Compose for writing the Android app.
collection(users)
->documents (all users for eg: sd3f3fvv3ac)
- name:""
- phone:1234
- contacts: array(all phone numbers)
So I want all those users/documents whose phone number is in the contacts array of the current document/user I am referring to.
I want something similar to this we might have done in SQL.
select * from users where phone IN (select contacts from users where user_id = {current user})
Solution 1:[1]
val citiesRef = db.collection("users")
citiesRef.whereArrayContains("contacts", phone).get()
.addOnSuccessListener { result ->
//read data
}
.addOnFailureListener {
//erormessage
}
}
With this code, the contacts that are the same as the phone number you wrote in the phone section are listed.
Solution 2:[2]
There is no way you can get only the users that have their phone number present in the contacts
array in a single go. So you have to query the users
collection twice, once to get the phone number, and second to verify if that number is present in the array. So the following lines of code will do the trick:
val db = Firebase.firestore
val usersRef = db.collection("users")
usersRef.get().addOnCompleteListener { usersTask ->
if (usersTask.isSuccessful) {
for (userDoc in usersTask.result) {
val phone = userDoc.getString("phone")
phone?.let {
usersRef.whereArrayContains("contacts", phone).get().addOnCompleteListener {
if (it.isSuccessful) {
for (doc in it.result) {
val name = doc.getString("name")
Log.d(TAG,"$name")
}
}
}
}
}
}
}
The result in the logcat will be the name of all users who have their phone number added to the contacts
array.
P.S.
I've seen that you're trying to use Jetpack Compose for building your app, a case in which I recommend your read the following article where I have explained how you can do that in clean architecture:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ă–mer Seyfettin Yavuzyi?it |
Solution 2 |