2

I have a collection user where I store all user data.
Now, my question is how I can get only those documents, where the email is not equal to the current user's email.

Firestore.instance.collection(USERS_COLLECTION).where("email",isLessThan: _useremail).snapshots(),
              builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot,) {
                if (!snapshot.hasData)
                  return new Container(child: Text(""),);
                var documentsLength = snapshot.data.documents.length;
                int rand = new Math.Random().nextInt(documentsLength.toInt());
creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402
Hitanshu Gogoi
  • 957
  • 3
  • 15
  • 24
  • 2
    Possible duplicate of [Firestore: how to perform a query with inequality / not equals](https://stackoverflow.com/questions/47251919/firestore-how-to-perform-a-query-with-inequality-not-equals) – Doug Stevenson Sep 10 '18 at 15:14

1 Answers1

3

For a general answer, please refer to this explanation Doug Stevenson gave.
In short, an inequality operation is not supported because of the way Firestore's indexes work.

In your specific problem, there is a simple way to solve it:
You can easily remove the single document you do not need client side, which will barely makes a difference in data and processing power usage.

Because I suppose that you will still want to use StreamBuilder, I will show a way to remove the document with your user's email from the List<DocumentSnapshot> you get from snapshot.data.docments:

StreamBuilder(
    stream: Firestore.instance
        .collection(USERS_COLLECTION)
        .snapshots(),
    builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
      if (!snapshot.hasData)
        return Container(child: Text(""));
      final List<DocumentSnapshot> documents = snapshot.data.documents.where((snapshot) => snapshot.data["email"] != _useremail);
      var documentsLength = documents.length;
      // ...
    });

The adjustments lie in the removal of the where in your query and the addition of the following line of code:

final List<DocumentSnapshot> documents = 
  snapshot.data.documents.where((snapshot) => snapshot.data["email"] != _useremail);

This removes all documents that are equal to _useremail, which is equivalent to your request.
Be aware that you will need to work with documents after that, in exactly the way I did with documentsLength.

This will also work if you want to remove multiple documents, but will obviously get more expensive the more "unnecessary" documents you retrieve. Thus, if you believe that you are doing too many document reads that are not necessarily required, you should think about adjusting your database structure.

Also, as mentioned here, you do not need to use the new keyword in Dart 2.

creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402