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.

3 Answers 3

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());
    });
  });
})
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot Frank. yesterday I wanted to chat with you. This solutions works that I expect.
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.

1 Comment

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
0
FirebaseFirestore.instance.collection('your collection name').where('favorite', arrayContains: 'Masha').snapshot();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.