0

I am trying to get all documents where the length of the "users" array is less than 2 and where the userId is not present already. I am doing the following query, but it is not executing correctly. What is the problem and how can I fix it? I just want all documents where there is only one entry in the array "users" and where the array does NOT contain the current userId.

await FirebaseFirestore.instance
  .collection('rooms')
  .where("users"[0], isNotEqualTo: userId)
  .where('users'[1], isEqualTo: null)
  .get()
  .then((snapshot) async {
// If no empty room is found, create room
if (snapshot.docs.isEmpty) {
  print("No empty room found, creating new room");
  roomId = await createRoom(userId);
  return roomId;
}

1 Answer 1

1

You can't query individual array elements in Firestore. You can only check whether an array contains a specific item.

It sounds like your array items have a specific meaning, in which case you should create (nested) fields that indicate/name the roles. For example:

participants: {
  creator: "uid1",
  receiver: "uid2"
}

With that you can then query the nested fields with dot notation:

.where("participants.creator", "!=", "uid1")
.where("participants.receiver", "==", null)

Keep in mind there that the participants.receiver field still has to exist in the latter case and have a value of null. Firestore can't filter in fields that don't exist.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks so much! Perfectly answered my question! Just one follow-up question: I am adding the participants in my room in the code like: "users": [userId1] - How do I add the nested field when doing the firestore query?
Adding a nested field, is done by passing the first snippet I have in my answer. Querying and updating a nested field is then done with dot syntax. Also see firebase.google.com/docs/firestore/manage-data/… for the latter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.