How to exclude an element from a Firestore query?

firestore search query
firestore query subcollection
firestore join query
firestore query array of objects
firestore query nested object
angular firestore query
firestore where or
flutter firestore query

I have a collection of users and I want to query all users from the database and display them in a RecyclerView except one, mine. This is my db schema:

users [collection]
  - uid [document]
     - uid: "fR5bih7SysccRu2Gu9990TeSSyg2"
     - username: "John"
     - age: 22
  - //other users

How to query the database like so:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
Query q = db.collection("users").whereNotEqualTo("uid", uid);

So I need this query object to be passed to a FirestoreRecyclerOptions object in order to display all the other users in RecyclerView.

Is this even possible? If not, how can I solve this? Thanks!

Edit:

options = new FirestoreRecyclerOptions.Builder<UserModel>()
        .setQuery(query, new SnapshotParser<UserModel>() {
            @NonNull
            @Override
            public UserModel parseSnapshot(@NonNull DocumentSnapshot snapshot) {
                UserModel userModel = documentSnapshot.toObject(UserModel.class);
                if (!userModel.getUid().equals(uid)) {
                    return userModel;
                } else {
                    return new UserModel();
                }
            }
        }).build();

After days and days of struggling with this issue, I finally found the answer. I could not solve this without the help of @Raj. Thank you so much @Raj for the patience and guidance.

First off all, according to the answer provided by @Frank van Puffelen in his answer from this post, I stopped searching for a solution that can help me pass two queries to a single adapter.

In this question, all that I wanted to achieve was to query the database to get all the users except one, me. So because we cannot combine two queries into a single instance, I found that we can combine the result of both queries. So I have created two queries:

FirebaseFirestore db = FirebaseFirestore.getInstance();
Query firstQuery = db.collection("users").whereLessThan("uid", uid);
Query secondQuery = db.collection("users").whereGreaterThan("uid", uid);

I'm having a UserModel (POJO) class for my user object. I found not one, but two ways to solve the problem. The first one would be to query the database to get all user objects that correspond to the first criteria and add them to a list. After that, query the database again and get the other user objects that correspond to the second criteria and add them to the same list. Now I have a list that contains all the users that I need but one, the one with that particular id from the queries. This is the code for future visitors:

firstQuery.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        List<UserModel> list = new ArrayList<>();
        if (task.isSuccessful()) {
            for (DocumentSnapshot document : task.getResult()) {
                UserModel userModel = document.toObject(UserModel.class);
                list.add(userModel);
            }

            secondQuery.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        for (DocumentSnapshot document : task.getResult()) {
                            UserModel userModel = document.toObject(UserModel.class);
                            list.add(userModel);
                        }

                        //Use the list of users
                    }
                }
            });
        }
    }
});

The second approach would be much shorter because I use Tasks.whenAllSuccess() like this:

Task firstTask = firstQuery.get();
Task secondTask = secondQuery.get();

Task combinedTask = Tasks.whenAllSuccess(firstTask, secondTask).addOnSuccessListener(new OnSuccessListener<List<Object>>() {
        @Override
        public void onSuccess(List<Object> list) {
            //This is the list that I wanted
        }
});

How to exclude certain data from Firestore query - firebase - html, How to exclude certain data from Firestore query - firebase. for a single object (​if the user clicks on the link for a specific object to go to the page for that object). The first one would be to query the database to get all user objects that correspond to the first criteria and add them to a list. After that, query the database again and get the other user objects that correspond to the second criteria and add them to the same list. Now I have a list that contains all the users that I need but one, the one with that particular id from the queries.


Firestore doesn't support not equal to operation. So you need to filter the data at the client side. Since in you case you only have one extra item you can filter it out.

For that you may need to build your own recycler implementation where when adding data to recycler adapter data layer, you restrict the data when ever it matches your != condition.

I haven't explored recycler implementation firebase provided so I cannot say it supports data manipulation to adapter data or not.

Here is a good resource to start implementing recycler view : https://www.androidhive.info/2016/01/android-working-with-recycler-view/

Exclude, Exclude. Contents; Inherited Method Summary. public abstract @interface Exclude implements Annotation. Marks a field as excluded from the database instance  Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies.


According to the official firestore documentation:-

Cloud Firestore does not support the following type of query:

Queries with a != clause. In this case, you should split the query into a greater-than query and a less-than query. For example, although the query clause where("age", "!=", "30") is not supported, you can get the same result set by combining two queries, one with the clause where("age", "<", "30") and one with the clause where("age", ">", 30).

If you are using FirestoreRecyclerAdapter then FirestoreRecyclerOptions will directly accepts the query using setQuery() method and hence not allows you to perform client side filtering.

If you try to apply filters in onBindViewHolder() while setting the data that might results in empty items in the recycler view. In order to resolve that refer Method 2.

So, the possible solution to your problem would be to create an integer field in your users collection under every document. Eg:-

users [collection]
  - uid [document]
     - uid: "fR5bih7SysccRu2Gu9990TeSSyg2"
     - username: "John"
     - age: 22
     - check: 100

In this I have created a 'check' variable whose value is 100. So, put value of 'check' in all other documents as less than 100. Now, you can easily make a query that finds documents with check<100 as:-

Query q = db.collection("users").whereLessThan("check", 100);

This will retrieve all your documents except the one you don't want. And while setting the data you can set other parameters skipping the check variable.

Method 2 (Client Side Filtering)

We can apply a check in onBindViewHolder() method that if the retrieved uid matches with current user uid then set the height of Recycler view as 0dp. As:-

ViewUserAdapter.java

public class ViewUserAdapter extends FirestoreRecyclerAdapter<User, ViewUserAdapter.ViewUserHolder>
{
    String uid;
    FirebaseAuth auth;

    public ViewUserAdapter(@NonNull FirestoreRecyclerOptions<User> options)
    {
        super(options);
        auth = FirebaseAuth.getInstance();
        uid = auth.getCurrentUser().getUid();
    }

    @Override
    protected void onBindViewHolder(@NonNull ViewUserHolder holder, int position, @NonNull User model)
    {
        DocumentSnapshot snapshot =  getSnapshots().getSnapshot(position);
        String id = snapshot.getId();

        if(uid.equals(id))
        {
            RecyclerView.LayoutParams param = (RecyclerView.LayoutParams)holder.itemView.getLayoutParams();
            param.height = 0;
            param.width = LinearLayout.LayoutParams.MATCH_PARENT;
            holder.itemView.setVisibility(View.VISIBLE);

        }
        else
        {
            holder.tvName.setText(model.name);
            holder.tvEmail.setText(model.email);
            holder.tvAge.setText(String.valueOf(model.age));
        }
    }
}

Perform simple and compound queries in Cloud Firestore, Cloud Firestore provides powerful query functionality for specifying which documents you want to retrieve from a collection or collection group. These queries  In part 16 of the Firestore tutorial, we will learn how to store, update and query arrays in Firestore. With the recent changes, it’s now possible to add and remove elements from an array with FieldValue arrayUnion and arrayRemove, and we can query for array members by adding whereArrayContains to a Query, where we pass the name of the field and the element we want to query for.


How to exclude an element from a Firestore query?, I have a collection of users and I want to query all users from the database and display them in a RecyclerView except one, mine. This is my db schema: users  By default, a query retrieves all documents that satisfy the query in ascending order by document ID. You can specify the sort order for your data using orderBy(), and you can limit the number of documents retrieved using limit(). Note: An orderBy() clause also filters for existence of the given field. The result set will not include documents that do not contain the given field.


Simpler and earlier client-side filtering (when you add items to your list):

  1. Get the current user's ID by using Firestore's standard method.
  2. Get the name of the doc for all the users in your user collection.
  3. Before adding the user to your RecyclerView list, check that the user it is about to add to your list is not the current user.

When done is this way, you can use the "not equals" method on the client side and not get into any Firestore issues. Another benefit is that you don't have to mess with your adapter or hide the view from a list-item you didn't want in the recycler.

public void getUsers(final ArrayList<Users> usersArrayList, final Adapter adapter) {

    CollectionReference usersCollectionRef = db.collection("users");

    Query query = usersCollectionRef
            .whereEqualTo("is_onboarded", true);

    query.get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        for (QueryDocumentSnapshot document : task.getResult()) {

                            final String otherUserID = document.getId();

                             FirebaseUser user = mAuth.getCurrentUser();
                             String currentUserID = user.getUid();

                            if (!otherUserID.equals(currentUserId)) {

                              usersArrayList.add(new User(otherUserID));
                              adapter.notifyDataSetChanged(); //Ensures users are visible immediately
                                            }
                                        } else {
                                            Log.d(TAG, "get failed with ", task.getException());
                                        }
                                    }
                                });
                            }

                        }
                    } else {
                        Log.d(TAG, "Error getting documents: ", task.getException());
                    }
                }
            });
}

FieldValue, The elements to remove from the array. Example. let documentRef = firestore.doc​('col  Non-existent ancestor documents appear in the console, but they do not appear in query results and snapshots. If you want to delete a document and all the documents within its subcollections, you must do so manually. For more information, see Delete Collections.


[Firebase] Cloud Firestore, “[Firebase] Cloud Firestore — Add, Set, Update, Delete Get data” is published by Aaron Lu. doc.data() is never undefined for query doc snapshots Cloud Firestore does not support the following types of queries: Queries with range filters on different fields, as described in the previous section. Logical OR queries. In this case, you should create a separate query for each OR condition and merge the query results in your app. Queries with a != clause.


Better Arrays in Cloud Firestore!, For starters, we've added the ability to query for elements within if you have multiple clients all trying to update or delete array elements at  You can use Firestore queries to get the document ID which corresponds to the field you want to keep unique. If the query returns null, that would mean that the database doesn’t contain that value., ergo, the username, in this case, is available or vice versa. Of course, you’d like to see some code sample, so let’s get to that.


Cloud Firestore, Hi there, I have the following problem: In a CollectionReference I can do the following: Firestore.instance.collection("jobs").where('user',  I want a query to to find any Client that does not have a particular account type, however I am unable to get any query working. Table Example:-Client Account 1111 1111GP1. 1111 1111GP1.1. 1111 1111SP20