7

I'm really new to firebase and to be honest I find queries hard to write. I'm working on a script in python using firebase_admin and i'd like the query/answer to be in python code, but in any other programming language is fine.

Here's my one of my document, one document contains photos set

photos: {
    id1: true
    id2: true
}

I want to be ale to retrieve all items where they have id1 in photos object, what would be the query for that?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

3 Answers3

11

As the Firebase documentation on simple queries shows:

# Create a reference to the photos collection
ref = db.collection('documents')

# Create a query against the collection
query_ref = ref.where(u'photos.id1', u'==', True)

For the . notation, see the documentation on fields in nested objects.

Note that you'll probably want to change your data model to use an array for this data, as arrays can now be used to model mathematical sets. With a an array like this in your document:

user: ['id1', 'id2']

You can then filter with:

photos_ref = db.collection('documents')

query = photos_ref.where(u'photos', u'array_contains', u'id1')

To add/remove items to this array-that-behaves-like-a-set, see the documentation on updating elements in an array.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
1

Based on Frank van Puffelen's solution, I was also able to use the dot notation to achieve the nested effect. Querying for objects where the assignment contains the current user's ID.

objectModel: {
      objectName: 'foo',
      otherField: 'bar',
      assignment: {
          installerIds: ['1', '2', '3'],
          otherfields: 'foobar'
      },
}

I was able to query like this

p = { field: 'assignment.installerIds', operator: 'array-contains', value: this.currentInstallerId} query = query.where(p.field, p.operator, p.value);

or in a more general format like Frank showed:

query_ref = ref.where('assignment.installerIds', 'array-contains', '2');
0

I think the where clause is changed now, won't take 3 parameters as mentioned above.

If anyone looking for the same answer, check below This is in Flutter, but the syntax is similar

    final snapShot = await FirebaseFirestore.instance.collection('documents')
    .where('photos. id1', isEqualTo: true)
    .get();

    final document = snapShot.docs.first.data();
Heshan Sandeepa
  • 3,388
  • 2
  • 35
  • 45