23

With firestore, how do I write a query to find documents that have an undefined field?

For example, here's a firestore collection with two documents:

{
  users: { // <- the collection
    a: { // <- the document
      active: true,
      profile: {
        first_name: 'Homer',
        last_name: 'Simpson',
      }
    },
    b:
      active: true
    }
  }
}

(Here's screenshots from the firestore console): Document 'a' , Document 'b'

Given the above firestore data, I want to do something like this:
firestore().collection('users').where('profile', '==', undefined) (which is not a valid query for firestore)

How can I write a query to retrieve all documents (users) where a certain field (profile) does NOT exist?

Thanks!

zero-signal
  • 231
  • 2
  • 5
  • 7
    It's not possible to query for documents based on a missing field. Typically you'll want to include a marker value for that field in each document, such as `null`. See https://stackoverflow.com/questions/46806860/how-to-query-cloud-firestore-for-non-existing-keys-of-documents – Frank van Puffelen Apr 10 '18 at 19:44
  • 2
    Bummer, I was hoping I wouldn't have to include a marker value. Thanks @FrankvanPuffelen! – zero-signal Apr 10 '18 at 20:14
  • 6
    why google cannot do .where('profile', '==', undefined) . sooo sad... – mili Mar 16 '19 at 07:59
  • 4
    I guess because a missing fields means a missing index... – Seb Jun 03 '19 at 19:32
  • 2
    This would have been nice to have for implicit data migration... – Mads Buch Dec 16 '19 at 14:17
  • 2
    @FrankvanPuffelen And if I'll already have thousands of documents. How to add the marker to the ones that don't have the marker. How to query those to add the marker? – InfoStatus Dec 22 '19 at 11:42
  • @InfoStatus AFAIK, you have to manually resave the entire Collection :( – RayfenWindspear Aug 20 '20 at 21:15
  • 2
    No, you can write a little function that iterates over your collection, checks for the marker, and adds it if the marker is not set. A developer does not have to do anything manually ;-) – Valentin Seehausen Sep 08 '20 at 08:15
  • @ValentinSeehausen how? – phongyewtong Oct 25 '20 at 12:27

0 Answers0