Firestore: How to query a map object inside a collection of documents?

enter image description herePlease let me know if I'm mistaken, but it appears that your query should actually work. as an experiment I added the structure you gave in the question and performed the query successfully in the firebase console.

Is this not what you are going for? I also made sure that the "in" operator works for this case as well. In this way you could ask which stories the user is owner & commenter.

enter image description here

This pulls in the correct results: enter image description here


Now you can filter ...

db
  .collection('orders')
  .where('orderDetails.status', '==', 'OPEN')

It will check if field orderDetails at property status equals to 'OPEN'


You cannot achieve this with your actual database structure in a way that you don't need to create an index for each user separately. To sovle this, you should duplicate your data. This practice is called denormalization and is a common practice when it comes to Firebase. If you are new to NoQSL databases, I recommend you see this video, Denormalization is normal with the Firebase Database for a better understanding. It is for Firebase realtime database but same rules apply to Cloud Firestore.

Also, when you are duplicating data, there is one thing that need to keep in mind. In the same way you are adding data, you need to maintain it. With other words, if you want to update/detele an item, you need to do it in every place that it exists.

That being said, you should create another collection named userStories, where you should add as documents all stories where a user is owner. So you database structure should look similar to this:

Firestore-root
   |
   --- userStories (collection)
         |
         --- uid (document)
              |
              --- allStories (collection)
                     |
                     --- storyId
                           |
                           --- role: "owner"

So a query like this:

db.collection('userStories').doc(${uid})
    .collection('allStories').where(`role`, '==', 'owner');

Will work perfectly fine.