title: How to query firebase realtime database in cloud code
body: <p>I am using Firebase cloud code and firebase realtime database. </p>
  
  <p>My database structure is:</p>
  
  <pre><code> -users
         -userid32
         -userid4734
            -flag=true  
         -userid722
            -flag=false
         -userid324
  </code></pre>
  
  <p>I want to query only the users who's field 'flag' is 'true' .</p>
  
  <p>What I am doing currently is going over all the users and checking one by one. But this is not efficient, because we have a lot of users in the database and it takes more than 10 seconds for the function to run:</p>
  
  <pre><code>const functions = require('firebase-functions');
  const admin = require("firebase-admin");
  admin.initializeApp(functions.config().firebase);
  
  exports.test1 = functions.https.onRequest((request, response) =&gt; {
      // Read Users from database
      //
      admin.database().ref('/users').once('value').then((snapshot) =&gt; {
          var values = snapshot.val(),
              current, 
              numOfRelevantUsers,
              res = {};       // Result string
  
              numOfRelevantUsers = 0;
  
          // Traverse through all users to check whether the user is eligible to get discount.
          for (val in values) 
          {
              current = values[val]; // Assign current user to avoid values[val] calls.
  
              // Do something with the user
          }
  
          ...
  });
  </code></pre>
  
  <p>Is there a more efficient way to make this query and get only the relevant records? (and not getting all of them and checking one by one?) </p>