Getting data from firebase with where using flutter - firebase

I will pull data from firebase according to the search word, but I had a problem using "where", how can I solve it?
i want to filter by value under name
FirebaseFirestore.instance
.collection('tedaviler')
.where("value.name", arrayContains: name)
.snapshots()
this is not working

Firestore's array-contains operation tests whether the value that you pass exists as an item in the array you identify. The value you pass must match the complete item in the array, there is no option to check just some of the properties.
In your code you have a condition:
.where("value.name", arrayContains: name)
This means you're looking for a field value at the root of the document, and then a subfield name under that. But your value field is an array, and it doesn't have a subfield name. Each item in the array may have a name subfield, but that is not the same.
So the condition is never met, and your query returns no documents.
If you want to test the items in the value array, you will have to know the entire item. If you have that, the condition becomes:
.where("value", arrayContains: {
"id": "IzotonikId123",
"name": "IV Izotonik %1",
"price": 8.88
})
If you want to be able to search on just the names, you'll need to add another array field to the document, where you keep just the (unique) value names:
valueNames: ["IV Izotonik %1", "IV Izotonik %2", "IV Izotonik %3"]
Then you can query for the existing of a specific name with:
.where("valueNames", arrayContains: name)

name is not an array in your DB. It is a string. You should try
FirebaseFirestore.instance
.collection('tedaviler')
.where("value.name", isEqualTo: name)
.snapshots()

Related

Querying FireBase FireStore Document in Flutter

I wants to achieve one query which i'm trying for few hours in FireStore Database, Please check the below image,
The Query I want to do is, In the document which I marked, will have a list of group id (combination of 2 userIds in each , userId1-userId2), I want to query this document by having one userId that contains in the group id (before or after hyphen) and returns a list of snapshots , which should be used for StreamBuilder in a list widget.
For Example:
I may have 'abcdefghijkl' userId, I want to check each document ID that contains this userId, and returns a list of snapshots which matches.
Thanks in Advance!
I don't think the query you want is possible, since there is no operation to check if a document id contains something. I would recommend adding a participants array to the document and than use an array-contains query, see also here.
There are several ways to achieve what you're after - a list of users relating to a given document - but I think you should rethink your data structure first. Each message document should have a users field that is an array of Firestore document IDs which would contain 1 or more document IDs of the users that this message relates to.
With that, you can easily query the database for all messages where a given user is referenced:
final messages = db
.collection('messages')
.where('users', arrayContains: userId)
.get();
BTW, to take things a step further, I would structure my data like this:
user {
displayName: '',
email: '',
messages: [
{
authorId: userId,
content: '',
users: [userId, ...],
sentOn: '',
},
...
]
}
With this you can do two things:
Fetch all messages created by the user:
final userMessages = db.doc(userId).collection('messages').get();
Fetch all messages where user participated:
final allUserMessages = db
.collectionGroup('messages')
.where('users', arrayContains: userId)
.get();
Check out the Firestore docs, as they have plenty of examples there.

how to query (filter) documents from firebase to flutter app based on a value nested in a List of Maps?

im trying to get documents from my 'Patients' Collection which contain an array of maps 'Appointments' based on the value of 'translator' key as shown here:
here is how im trying to query the documents but i guess im having a syntax error
static Stream<QuerySnapshot> getSpecificUserAppointments(String translatorName) {
return FirebaseFirestore.instance
.collection('Patients')
.where('appointments', arrayContains: translatorName)
.snapshots();
}
i also tried to filter this way
.where('appointments.translator', arrayContains: translatorName),
.where('appointments.translator', isEqualto: translatorName)
still not getting results
any help would be appreciated
The arrayContains operator checks whether the exact, complete item you specify exists in the array. So your check would only work if the appointments array contained an entry that has a single string as its value with translatorName.
If you want to check whether a certain name exists, add an additional array field to your document with translatorNames, where you keep just the (unique) names of the translators in the document. Then you can use that field to query:
return FirebaseFirestore.instance
.collection('Patients')
.where('translatorNames', arrayContains: translatorName)
.snapshots();

Firestore : Update only a key-val pair

We have a firestore collection, where each document has only one field names.
names contains a map.
Now if, I just want to update a single key value pair in that map, is there a way, other than:
await FirebaseFirestore.instance
.collection(namesCollectionName)
.doc(docId)
.update(savedNames.toJson())
.whenComplete(() => {developer.log("Update saved names success")})
.catchError((error) {
developer.log("Update saved names failed: $error");
throw Exception("Update saved names failed: $error");
});
This code updates the entire map.
I am not sure if there is a way to update just a key value pair. I felt it would be more efficient!
Firestore processes each entries in the map you pass as a set operation on that field.
If you want to update nested fields use . notation to mark that field. So say you store the full name for each user keyed on the Stack Overflow ID as a map under the names field, that'd be:
users
.doc('ABC123')
.update({'names.13076945': 'Nithin Sai'})
If your names field is an array and you want to add a certain name if it doesn't exist in there yet, that'd be an array-union, which looks like this:
users
.doc('ABC123')
.update({'names': FieldValue.arrayUnion(['Nithin Sai'])});

Retrieve field information form Firestore database

So I want to retrieve name of a user which is inside a field in firestore.
The whole sequence in given in image below.
I want to get the string value 'a' which is inside (chatroom->a_qaz->users->'a').
I am trying to get it with this code but its not working. How to get the field information.
getOtherUserByUsername() async {
return await FirebaseFirestore.instance
.collection("chatroom")
.doc("chatRoomId")
.get();
First of all, let's get the document from your collection.
collection.doc(), as per reference, gets the actual ID as parameter. In your case, you need to specify "a_qaz". After that, you get the document and then you can read the fields. Your code should look like this:
let chatRoom = await FirebaseFirestore.instance
.collection("chatroom")
.doc("a_qaz")
.get();
let users = chatRoom.get("users");
users will store, then, the list of users that's in that field.

Unable to get the documents after creating a query index

Code:
var querySnapshot = await Firestore //
.instance
.collection('collection')
.where('name', isEqualTo: ['foo'])
.orderBy('time')
.limit(1)
.getDocuments();
print('${querySnapshot.documents}'); // prints []
It returns empty List.
Database structure:
Index built
Indexing isn't an issue here. Given the query and document you're showing, I'd always expect it to return no results. You're using an array-contains type query on a field that isn't an array. Your name field is a string, and strings can't be matched by array-contains queries.
If you intended for name to be an array, you'll need to modify the document so that it is actually an array with the string "foo" in it.

Resources