Reputation: 389
I want to query firebase firestore data collection with two paramaters.
The collection: animals
"animals": {
"1": {
"animal1": "cat",
"animal2": "dog",
"animal3": "",
"animal4": ""
},
"2": {
"animal1": "dog",
"animal2": "cat",
"animal3": "",
"animal4": ""
},
"3": {
"animal1": "cat",
"animal2": "bird",
"animal3": "dog",
"animal4": ""
},
"4": {
"animal1": "wolf",
"animal2": "dog",
"animal3": "bird",
"animal4": ""
},
"5": {
"animal1": "turtle",
"animal2": "dog",
"animal3": "wolf",
"animal4": "cat"
},
"6": {
"animal1": "dog",
"animal2": "wolf",
"animal3": "turtle",
"animal4": "bear"
},
"7": {
"animal1": "spider",
"animal2": "beatle",
"animal3": "butterfly",
"animal4": "Cat"
}
}
I want getting list datas that include cat and dog. There is information In here Logical OR queries. In this case, you should create a separate query for each OR condition and merge the query results in your app.
I don't know how many separate query I need?
let param1 = 'cat';
let param2 = 'dog';
let query1 = db.collection('animals').where('animal1', '==', param1);
let query2 = db.collection('animals').where('animal2', '==', param1);
let query3 = db.collection('animals').where('animal3', '==', param2);
let query4 = db.collection('animals').where('animal4', '==', param3);
Upvotes: 0
Views: 495
Reputation: 83058
As you have noted "you should create a separate query for each OR condition and merge the query results in your app". Since, with your data model, you have 4 fields (animal1
to animal4
) you will need to create 4 queries for each param
value you want to test for.
So in case of 2 params, as follows:
let param1 = 'cat';
let param2 = 'dog';
you will have to merge the results of 2*4 queries....
There is a possibility to decrease this number if you change your data model and use an array for storing the animal
values. You could then take advantage of the array_contains
operator.
Proposed data model:
"animals": {
"1": {
"animalArray":
[
0: "cat",
1: "dog"
]
},
"2": {
"animalArray":
[
0: "turtle",
1: "dog",
2: "wolf",
3: "bear",
]
}
.....
}
With our example of two params
, you would need two queries only, as follows:
let query1 = db.collection('animals').where("animalArray", "array-contains", param1);
let query2 = db.collection('animals').where("animalArray", "array-contains", param2);
Upvotes: 1