Reputation: 1141
I have a collection dinosaurs
with documents of this structure:
doc#1:
name: "Tyrannosaurus rex",
dominantColors: [
"beige",
"blue",
"green"
]
doc#2:
name: "Velociraptor",
dominantColors: [
"green",
"orange",
"white"
]
I want to query the collection by color name (for example: green
) to get documents sorted by color's position in dominantColors
array. First get the documents in which green
occurs higher in the array, then those in which it is lower. So, in the provided case I would get doc#2
first, then doc#1
.
Each dominantColors
array contains 3 elements, with elements sorted from most dominant to least.
I am looking through documentation, but am not able to find a solution. Maybe I need a different data structure altogether?
Upvotes: 0
Views: 129
Reputation: 317968
Cloud Firestore doesn't support querying arrays by ranked index. The only way you can query an array is using an array-contains type query.
What you could do instead is organize your colors using maps where the color is the key and their rank is the value:
name: "Tyrannosaurus rex",
dominantColors: {
"beige": 1,
"blue": 2,
"green": 3
}
Then you can order the query by the value of the map's property. So, in JavaScript, it would be something like this:
firebase
.collection('dinosaurs')
.where('dominantColors.green', '>', 0)
.orderBy('dominantColors.green')
Upvotes: 2