Home > Back-end >  FireStore query how to query arrays from the database
FireStore query how to query arrays from the database

Time:02-23

I am trying to query the database to get a certain document that contains an array which has both the userid and id

const userChatQuery = query(collectionGroup(db, userchat), where(user, 'array-contains', [userId, id]));

I want to retrieve the document that contains the array that contains those two id strings regardless of order but they have to contain both of those strings.

What would be the best way to go about it ?

CodePudding user response:

What you've described is not possible using a single query.

Firstly, array-contains only accepts single values as a parameter, not arrays of values to find. Its purpose is to find matching documents where that one value is an element of the named array field.

If you could make the assumption that the array can have only two values, and those values only occur in the same order, then you might be able to perform a simple equality filter given the exact array you're looking for. Just feed the query the exact array you're looking for.

If you can't make those assumptions, you could try two array-contains queries, one for each of the ID strings, and examine the results of both queries to find where they overlap.

But, to be honest, you're probably better off restructuring your database not to use arrays at all. If you have values with a distinct purpose, they should not be in an array at all. They should be individual fields that you can filter normally. It seems really odd to me that you're working with arrays for this data. The data modeling you have right now does not meet your query requirements at all, which is a major problem when working with NoSQL type databases. With NoSQL, you typically figure out how you want to query the data first, then model your data to suit those requirements.

  • Related