Ask Your Question
3

How can the array in Firestore be sorted or filtered by the number of elements it contains?

asked 2022-01-06 11:00:00 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-12-08 17:00:00 +0000

pufferfish gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-01-06 11:00:00 +0000

Seen: 7 times

Last updated: Dec 08 '21