71

I want select from Firestore collection just articles written NOT by me.
Is it really so hard?

Every article has field "owner_uid".

Thats it:
I JUST want to write equivalent to "select * from articles where uid<>request.auth.uid"

TL;DR: solution found already: usages for languages/platforms: https://firebase.google.com/docs/firestore/query-data/queries#kotlin+ktx_5

1
  • Firestore now supports "where in" operator. Check my answer and update accepted answer
    – TSR
    Sep 13, 2020 at 15:09

7 Answers 7

95

EDIT Sep 18 2020

The Firebase release notes suggest there are now not-in and != queries. (Proper documentation is now available.)

  • not-in finds documents where a specified field’s value is not in a specified array.
  • != finds documents where a specified field's value does not equal the specified value.

Neither query operator will match documents where the specified field is not present. Be sure the see the documentation for the syntax for your language.

ORIGINAL ANSWER

Firestore doesn't provide inequality checks. According to the documentation:

The where() method takes three parameters: a field to filter on, a comparison operation, and a value. The comparison can be <, <=, ==, >, or >=.

Inequality operations don't scale like other operations that use an index. Firestore indexes are good for range queries. With this type of index, for an inequality query, the backend would still have to scan every document in the collection in order to come up with results, and that's extremely bad for performance when the number of documents grows large.

If you need to filter your results to remove particular items, you can still do that locally.

You also have the option of using multiple queries to exclude a distinct value. Something like this, if you want everything except 12. Query for value < 12, then query for value > 12, then merge the results in the client.

24
  • 13
    locally but how? If collection "articles" has 10 thousands articles readed by me it means I have to query this collection with pagination crazy amount of times before i will reach UNreaded articles. Nov 12, 2017 at 19:30
  • 1
    <br>for example, how to get only articles i DONT read already?<br> storing readed_article_ids in my user Firestore Document will enlarge my user document and every firestore doc has limit in 1mb - some day readed_article_ids Firestore Array within my user document will exceed this threshold.<br> So confused :((( Nov 12, 2017 at 19:34
  • 195
    Such annoying lacking of basic functionality makes me regret that I've picked Google Firebase as BaaS Nov 22, 2017 at 13:19
  • 11
    There's no minefields here. Like any nosql database, you have to learn how to model your data in a way that suits your anticipated queries. Nov 23, 2017 at 18:17
  • 6
    So I've made an app for creating articles. I've been surprised, when I haven't found any solution of how to show a list of articles created by other users. local filtering is bullshit in million(just one!) articles case. ^( Nov 28, 2017 at 19:29
6

For android it should be easy implement with Task Api. Newbie example:

    FirebaseFirestore db = FirebaseFirestore.getInstance();
    Query lessQuery = db.collection("users").whereLessThan("uid", currentUid);
    Query greaterQuery = db.collection("users").whereGreaterThan("uid", currentUid);
    Task lessQuery Task = firstQuery.get();
    Task greaterQuery = secondQuery.get();

    Task combinedTask = Tasks.whenAllSuccess(lessQuery , greaterQuery)
                             .addOnSuccessListener(new OnSuccessListener<List<Object>>() {
        @Override
        public void onSuccess(List<Object> list) {

            //This is the list of "users" collection without user with currentUid
        }
    });

Also, with this you can combine any set of queries.

For web there is rxfire

1
  • is this best practice? What are other solutions if i am using firestore paging adapter from firebase-ui Mar 18, 2020 at 8:54
4

This is an example of how I solved the problem in JavaScript:

let articlesToDisplay = await db
  .collection('articles')
  .get()
  .then((snapshot) => {
    let notMyArticles = snapshot.docs.filter( (article) => 
      article.data().owner_uid !== request.auth.uid
    )
    return notMyArticles
  })

It fetches all documents and uses Array.prototype.filter() to filter out the ones you don't want. This can be run server-side or client-side.

2
  • 4
    Did you count reads from your db in Firebase console? I think in this way you always read all the 'atricles' db graph, and only then you filter items - which is too expensive by your server memory+cpu usage in the case of huge graph size Mar 1, 2020 at 12:10
  • Yes, as stated this solution reads all documents from the collection. Inappropriate for large collections. You could filter on date to get articles from, say, the last week only to reduce the size, but depends on the use case.
    – Darren G
    Mar 2, 2020 at 19:24
0

Updating the answer of Darren G, which caused "TypeError: Converting circular structure to JSON". When we perform the filter operation, the whole firebase object was added back to the array instead of just the data. We can solve this by chaining the filter method with the map method.

let articles = []
let articlesRefs = await db.collection('articles').get();

articles = articlesRefs.docs
           .filter((article) => article.data.uid !== request.auth.uid) //Get Filtered Docs
           .map((article) => article.data()); //Process Docs to Data

return articles

FYI: This is an expensive operation because you will fetching all the articles from database and then filtering them locallly.

0
  1. Track all user id in a single document (or two)

  2. filter unwanted id out

  3. Use "where in"


var mylistofidwherenotme =  // code to fetch the single document where you tracked all user id, then filter yourself out


database.collection("articles").where("blogId", "in", mylistofidwherenotme)

1
  • you can't filter unwanted id's out from the document and you also can't fetch every time all the ids to perform filtering locally - we speak about huge database Sep 16, 2020 at 17:16
-1
let query = docRef.where('role','>',user_role).where('role','<',user_role).get()

This is not functioning as the "not equal" operation in firestore with string values

3
  • 7
    I don't think chaining .where would operate like OR logic, it should be AND logic. So this probably won't work? Sep 23, 2019 at 8:49
  • 3
    You have to query separately for both conditions and join results, thus increasing the number of reads operation and sucking money out of your pocket
    – Voonic
    Jan 26, 2020 at 18:52
  • will return an empty list Jun 15, 2020 at 12:30
-1

You can filter the array of objects within the javascript code.

var data=[Object,Object,Object] // this is your object array
var newArray = data.filter(function(el) {
   return el.gender != 'Male';
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.