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;
}
cipano
  • 107
  • 1
  • 8

1 Answers1

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.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 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? – cipano Nov 05 '22 at 19:16
  • 1
    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 https://firebase.google.com/docs/firestore/manage-data/add-data#update_fields_in_nested_objects for the latter. – Frank van Puffelen Nov 05 '22 at 19:19