0Pricing
Firebase Auth & Realtime Database Apps · 강의

기본 데이터 쿼리

실시간 데이터베이스에서 특정 데이터 하위 집합을 가져오는 기본 쿼리를 실행합니다.

기본 데이터 쿼리은(는) CoddyKit의 무료 Firebase Auth & Realtime Database Apps 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Firebase Auth & Realtime Database Apps 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Firebase Auth & Realtime Database Apps 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Intro to Database Queries

Welcome to Basic Data Queries! In this lesson, you'll learn how to fetch specific data from your Firebase Realtime Database efficiently.

A database query is like asking a precise question to your database. Instead of getting all the data, you retrieve only what you need, saving bandwidth and improving app performance.

We'll use the Firebase JavaScript SDK for our examples. The core starting point for any query is a firebase.database().ref(), which points to a specific location in your database.

Sample Data & Initial Setup

First, let's set up a basic HTML page to interact with Firebase and populate some sample data. This will serve as your 'main entry point' for our examples.

We'll use a simple 'users' dataset where each user has a name, age, and city.

Important: Replace YOUR_API_KEY, YOUR_PROJECT_ID, etc., with your actual Firebase project configuration.

<!DOCTYPE html>
<html>
<head>
  <title>Firebase Query Demo</title>
  <script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js"></script>
  <script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-database.js"></script>
</head>
<body>
  <h1>Firebase Query Setup</h1>
  <p>Check your browser's console for output.</p>

  <script>
    // Your Firebase project configuration
    const firebaseConfig = {
      apiKey: "YOUR_API_KEY",
      authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
      databaseURL: "https://YOUR_PROJECT_ID-default-rtdb.firebaseio.com",
      projectId: "YOUR_PROJECT_ID",
      storageBucket: "YOUR_PROJECT_ID.appspot.com",
      messagingSenderId: "YOUR_SENDER_ID",
      appId: "YOUR_APP_ID"
    };

    // Initialize Firebase
    firebase.initializeApp(firebaseConfig);
    const db = firebase.database();

    // Reference to the 'users' node
    const usersRef = db.ref('users');

    // Sample data to write (only if not already present)
    const sampleUsers = {
      "user1": { "name": "Alice", "age": 30, "city": "New York" },
      "user2": { "name": "Bob", "age": 25, "city": "London" },
      "user3": { "name": "Charlie", "age": 35, "city": "New York" },
      "user4": { "name": "David", "age": 25, "city": "Paris" }
    };

    // Write data to the database (only once for demo)
    usersRef.once('value', snapshot => {
      if (!snapshot.exists()) {
        usersRef.set(sampleUsers)
          .then(() => console.log('Sample data written successfully!'))
          .catch(error => console.error('Error writing sample data:', error));
      } else {
        console.log('Sample data already exists. Skipping write.');
      }
    });

    console.log('Firebase initialized and sample data check complete.');
  </script>
</body>
</html>

Ordering Data: orderByChild()

One of the most common ways to sort your data is using orderByChild(). This method sorts the children of a given reference by the value of a specified child key.

For example, if you have a list of users and each user has an 'age' property, you can use orderByChild('age') to get them sorted by age.

  • It takes one argument: the name of the child key to order by.
  • Results are returned in ascending order by default.

orderByChild() in Action

Let's retrieve our users, ordered by their age. The output will show users from youngest to oldest.

Run this code and check the console output or the list on the page!

<!DOCTYPE html>
<html>
<head>
  <title>OrderByChild Demo</title>
  <script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js"></script>
  <script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-database.js"></script>
</head>
<body>
  <h1>OrderByChild Query</h1>
  <p>Users ordered by age:</p>
  <ul id="user-list"></ul>

  <script>
    const firebaseConfig = {
      apiKey: "YOUR_API_KEY",
      authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
      databaseURL: "https://YOUR_PROJECT_ID-default-rtdb.firebaseio.com",
      projectId: "YOUR_PROJECT_ID",
      storageBucket: "YOUR_PROJECT_ID.appspot.com",
      messagingSenderId: "YOUR_SENDER_ID",
      appId: "YOUR_APP_ID"
    };
    firebase.initializeApp(firebaseConfig);
    const db = firebase.database();
    const usersRef = db.ref('users');

    usersRef.orderByChild('age').on('value', (snapshot) => {
      const userList = document.getElementById('user-list');
      userList.innerHTML = ''; // Clear previous list
      snapshot.forEach((childSnapshot) => {
        const user = childSnapshot.val();
        const li = document.createElement('li');
        li.textContent = `${user.name} (Age: ${user.age}, City: ${user.city})`;
        userList.appendChild(li);
      });
      console.log('Users ordered by age:', snapshot.val());
    }, (error) => {
      console.error('Error fetching data:', error);
    });
  </script>
</body>
</html>

Other Ordering: orderByKey() & orderByValue()

Besides orderByChild(), Firebase Realtime Database offers two other ordering methods:

  • orderByKey(): Sorts the results by the keys of the children. This is useful when your keys represent IDs or sequential numbers.
  • orderByValue(): Used when the children themselves are simple primitive values (strings, numbers, booleans) rather than objects. It sorts by these values directly.

Remember, you can only use one orderBy method per query.

orderByKey() Example

Let's see orderByKey() in action. This will sort our users by their unique user IDs (e.g., 'user1', 'user2').

This is often the default behavior if no orderBy is specified, but explicitly using it can make your intent clearer.

<!DOCTYPE html>
<html>
<head>
  <title>OrderByKey Demo</title>
  <script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js"></script>
  <script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-database.js"></script>
</head>
<body>
  <h1>OrderByKey Query</h1>
  <p>Users ordered by key:</p>
  <ul id="user-list"></ul>

  <script>
    const firebaseConfig = {
      apiKey: "YOUR_API_KEY",
      authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
      databaseURL: "https://YOUR_PROJECT_ID-default-rtdb.firebaseio.com",
      projectId: "YOUR_PROJECT_ID",
      storageBucket: "YOUR_PROJECT_ID.appspot.com",
      messagingSenderId: "YOUR_SENDER_ID",
      appId: "YOUR_APP_ID"
    };
    firebase.initializeApp(firebaseConfig);
    const db = firebase.database();
    const usersRef = db.ref('users');

    usersRef.orderByKey().on('value', (snapshot) => {
      const userList = document.getElementById('user-list');
      userList.innerHTML = '';
      snapshot.forEach((childSnapshot) => {
        const user = childSnapshot.val();
        const key = childSnapshot.key;
        const li = document.createElement('li');
        li.textContent = `ID: ${key}, Name: ${user.name} (Age: ${user.age})`;
        userList.appendChild(li);
      });
      console.log('Users ordered by key:', snapshot.val());
    }, (error) => {
      console.error('Error fetching data:', error);
    });
  </script>
</body>
</html>

Limiting Results: limitToFirst()

Often, you don't need all results, just a subset. limitToFirst() and limitToLast() allow you to specify the maximum number of items to retrieve.

  • limitToFirst(n): Returns the first n items after ordering.
  • limitToLast(n): Returns the last n items after ordering.

These are always used in conjunction with one of the orderBy methods to ensure a consistent result set.

limitToFirst() Example

Let's fetch only the first two users when ordered by age. This is useful for leaderboards or showing recent activity.

Notice how we combine orderByChild() with limitToFirst() to get a specific slice of data.

<!DOCTYPE html>
<html>
<head>
  <title>LimitToFirst Demo</title>
  <script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js"></script>
  <script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-database.js"></script>
</head>
<body>
  <h1>LimitToFirst Query</h1>
  <p>First 2 users ordered by age:</p>
  <ul id="user-list"></ul>

  <script>
    const firebaseConfig = {
      apiKey: "YOUR_API_KEY",
      authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
      databaseURL: "https://YOUR_PROJECT_ID-default-rtdb.firebaseio.com",
      projectId: "YOUR_PROJECT_ID",
      storageBucket: "YOUR_PROJECT_ID.appspot.com",
      messagingSenderId: "YOUR_SENDER_ID",
      appId: "YOUR_APP_ID"
    };
    firebase.initializeApp(firebaseConfig);
    const db = firebase.database();
    const usersRef = db.ref('users');

    usersRef.orderByChild('age').limitToFirst(2).on('value', (snapshot) => {
      const userList = document.getElementById('user-list');
      userList.innerHTML = '';
      snapshot.forEach((childSnapshot) => {
        const user = childSnapshot.val();
        const li = document.createElement('li');
        li.textContent = `${user.name} (Age: ${user.age}, City: ${user.city})`;
        userList.appendChild(li);
      });
      console.log('First 2 users by age:', snapshot.val());
    }, (error) => {
      console.error('Error fetching data:', error);
    });
  </script>
</body>
</html>

Filtering with equalTo()

To find items that exactly match a specific value, you use equalTo(). This method is almost always combined with one of the orderBy methods.

  • It takes one argument: the exact value to match.
  • For example, orderByChild('city').equalTo('New York') would find all users whose city is 'New York'.

Remember, equalTo() needs an orderBy clause to know which child or key to compare against.

equalTo() Example

Let's retrieve all users who live in 'New York'. We'll order by city and then filter for an exact match.

This query is powerful for finding specific records based on their attributes.

<!DOCTYPE html>
<html>
<head>
  <title>EqualTo Demo</title>
  <script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js"></script>
  <script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-database.js"></script>
</head>
<body>
  <h1>EqualTo Query</h1>
  <p>Users living in New York:</p>
  <ul id="user-list"></ul>

  <script>
    const firebaseConfig = {
      apiKey: "YOUR_API_KEY",
      authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
      databaseURL: "https://YOUR_PROJECT_ID-default-rtdb.firebaseio.com",
      projectId: "YOUR_PROJECT_ID",
      storageBucket: "YOUR_PROJECT_ID.appspot.com",
      messagingSenderId: "YOUR_SENDER_ID",
      appId: "YOUR_APP_ID"
    };
    firebase.initializeApp(firebaseConfig);
    const db = firebase.database();
    const usersRef = db.ref('users');

    usersRef.orderByChild('city').equalTo('New York').on('value', (snapshot) => {
      const userList = document.getElementById('user-list');
      userList.innerHTML = '';
      snapshot.forEach((childSnapshot) => {
        const user = childSnapshot.val();
        const li = document.createElement('li');
        li.textContent = `${user.name} (Age: ${user.age}, City: ${user.city})`;
        userList.appendChild(li);
      });
      console.log('Users in New York:', snapshot.val());
    }, (error) => {
      console.error('Error fetching data:', error);
    });
  </script>
</body>
</html>

Quick Check: Basic Queries

Given a users node with children like { name: 'Alice', age: 30, city: 'New York' }, which query correctly retrieves users from 'New York'?

Recap: Basic Data Queries

Congratulations! You've completed the basics of querying your Firebase Realtime Database.

We covered:

  • Using orderByChild() to sort data by a specific property.
  • orderByKey() and orderByValue() for different sorting needs.
  • Restricting results with limitToFirst() and limitToLast().
  • Filtering for exact matches using equalTo(), always with an orderBy clause.

These fundamental querying techniques are crucial for building efficient and responsive applications. In the next lesson, we'll dive deeper into more advanced filtering and ordering!

자주 묻는 질문

“기본 데이터 쿼리” 강의는 무료인가요?

네 — “기본 데이터 쿼리” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Firebase Auth & Realtime Database Apps 강의 전체를 잠금 해제할 수 있습니다. Firebase Auth & Realtime Database Apps 강의에는 총 4개의 강의가 포함되어 있습니다.

“기본 데이터 쿼리”에서 뭘 배우나요?

실시간 데이터베이스에서 특정 데이터 하위 집합을 가져오는 기본 쿼리를 실행합니다. 브라우저에서 직접 실행하는 실습 코드로 Firebase Auth & Realtime Database Apps을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Firebase Auth & Realtime Database Apps을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Firebase Auth & Realtime Database Apps은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“기본 데이터 쿼리” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Firebase Auth & Realtime Database Apps 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Firebase Auth & Realtime Database Apps 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 기본 데이터 쿼리
  2. 데이터 필터링 및 정렬
  3. 데이터 페이지 매김 기법
  4. 성능을 위한 쿼리 인덱싱
← Firebase Auth & Realtime Database Apps(으)로 돌아가기