Firestore: how to perform a query with inequality / not equals

Solution 1:

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.

Solution 2:

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

Solution 3:

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.