I am working on a browser game and I have a collection in firestore that looks like this:
{
title: "doc 1",
requirements: {
level: {
min: 2,
max: 3
}
}
},
{
title: "doc 2",
requirements: {
level: {
min: 6,
max: 8
}
}
},
{
title: "doc 3",
requirements: {
level: {
min: 8,
max: 9
}
}
}
Is there any way to query for all documents, that match a given level like when I have a level of 8 I only want to fetch the documents "doc 2" and "doc 3" because the level requirements match?
I tried with something like
ref.where("requirements.level.min", "<=", level);
ref.where("requirements.level.max", ">=", level);
I also tried to change the structure in my documents to this:
{
title: "doc 1",
requirements: {
level: [2, 3]
}
},
{
title: "doc 2",
requirements: {
level: [6, 7, 8]
}
}
and filter it like this
ref.where("requirements.level", "array-contains", level)
But firestore always returns me all documents.
There is no way to get documents from different collections or sub-collections in a single query. Firestore doesn't support queries across different collections in one go unless we are using a collection group query.
In Query: With the in query, you can query a specific field for multiple values (up to 10) in a single query. You do this by passing a list containing all the values you want to search in, and Cloud Firestore will match any document whose field equals one of those values.
A QuerySnapshot contains zero or more QueryDocumentSnapshot objects representing the results of a query. The documents can be accessed as an array via the docs property or enumerated using the forEach method. The number of documents can be determined via the empty and size properties.
Array contains seems to be correct choice here. I've checked your example - recreated quite similar structure in my firestore (other doc has same structure but levels from 5 to 7) and run these queries:
const docs = firebase.firestore().collection('docs');
docs.where('requirements.levels','array-contains',2).get().then((snap) => {
console.log(snap.docs.length); //<- outputs 1, correct
});
docs.where('requirements.levels','array-contains',4).get().then((snap) => {
console.log(snap.docs.length); //<- outputs 0, correct
});
docs.where('requirements.levels','array-contains',5).get().then((snap) => {
console.log(snap.docs.length); //<- outputs 1, correct
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With