Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Firestore does not support sorting or filtering of arrays by the number of elements it contains directly. However, you can create a separate field in your document to store the length of the array and use it for sorting and filtering.

For example, suppose you have a collection of documents called "books". Each document has a field called "authors", which is an array containing the names of the authors of that book. To sort the books by the number of authors, you could add a field called "authorCount" to each document and update it whenever the "authors" field changes:

db.collection("books").doc("book1").set({
    authors: ["Alice", "Bob", "Charlie"],
    authorCount: 3,
});
db.collection("books").doc("book2").set({
    authors: ["Alice", "Bob"],
    authorCount: 2,
});
db.collection("books").doc("book3").set({
    authors: ["Alice"],
    authorCount: 1,
});

Then, you can use a query to sort the collection:

db.collection("books").orderBy("authorCount", "desc").get().then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
        console.log(doc.id, "=>", doc.data());
    });
});

This will return the documents sorted by the number of authors in descending order. You can also use the "where" method to filter the collection by the number of authors:

db.collection("books").where("authorCount", ">=", 2).get().then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
        console.log(doc.id, "=>", doc.data());
    });
});

This will return only the documents where the "authorCount" field is greater than or equal to 2.