4

Is there any way to on Firebae to filter data in an array?

I have this model on my Firebase:

-KABIGeWnBMUKjLTcvp8  
  deviceToken:"7DE60240CB4B712F05A009F32358610C1327917E7E68409..."
  favorites
    0:"Masha"
    1:"moksha"
  name:"juan"

And the problem is that I can't find any method to get all "users" that contain a certain value on the "favorites" array field.

Community
  • 1
  • 1
juanObrach
  • 158
  • 1
  • 5
  • 14

3 Answers3

6

Nope, that's not an option See firebase equivalent to sql where in ().

Instead: invert your data structure to make this query possible:

items_by_favorites
  "Masha"
    "-KABIGeWnBMUKjLTcvp8"
  "moksha"
    "-KABIGeWnBMUKjLTcvp8"

Now you can look up the item keys for Masha with a simple read: ref.child('items_by_favorites/Masha') and then load each item:

ref.child('items_by_favorites/Masha').on('value', function(snapshot) {
  snapshot.forEach(function(childSnapshot) {
    var key = childSnapshot.key();
    ref.child('items').child(key).once('value', function(itemSnapshot) {
      console.log(itemSnapshot.val());
    });
  });
})
Community
  • 1
  • 1
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
3

First of all your question is answered deep in the guide for retrieving data, which is where I got this answer. It's under complex queries, then range queries, should you want more info.

var ref = new Firebase("https://dinosaur-facts.firebaseio.com/dinosaurs");
ref.orderByChild("height").equalTo(25).on("child_added", function(snapshot) {
  console.log(snapshot.key());
});

The basic idea is that you need to first order the reference by a common child value, and then call .equalTo() to end up with a query that yields what you want.

Also you can call order by child like

ref.orderByChild("height/sublevel")

To drill deeper in the tree.

wolf123450
  • 103
  • 1
  • 7
  • 1
    Thanks, but this doesn't respond my question. I want to get all "artists" that match certain values on "favorites" array field. EqualTo doesn't work on this array field – juanObrach Feb 10 '16 at 20:20
0
FirebaseFirestore.instance.collection('your collection name').where('favorite', arrayContains: 'Masha').snapshot();
MD. Saffan Alvy
  • 182
  • 2
  • 15