目录

Querying Data

Cloud DB uses the query() method to query objects and provides various predicate query methods, such as equalTo(), notEqualTo(), and in(). By using one or more chained predicates, you can query objects that meet the specific query conditions from a Cloud DB zone, or sort query results or limit the number of returned query results by using the corresponding predicates. For details about query conditions, please refer to DatabaseQuery.

The app directly queries data from the Cloud DB zone server and does not cache data locally.

  • You can query the data of only one object type at a time.

  • When calling the data query method, there are two ways to return the result: either by returning a Promise object or by passing a callback object in the parameters. The following example explains the Promise approach in detail.

Constraints

This feature supports phones and tablets by default. Starting from version 5.1.0(18), support for wearables is added. From version 5.1.1(19), TVs are also supported. From version 6.1.0(23), PCs/2-in-1 devices are supported as well.

Prerequisites

You have initialized database access.

Simple Query

You can obtain all objects of an object type when no query conditions are set. You can also specify a query condition to obtain desired objects.

  1. Import required modules.

    import { cloudDatabase } from '@kit.CloudFoundationKit';
    import { BookInfo } from '../model/BookInfo';
    import { hilog } from '@kit.PerformanceAnalysisKit';
    import { BusinessError } from '@kit.BasicServicesKit';
  2. Query all data of the BookInfo object type.

    let condition = new cloudDatabase.DatabaseQuery(BookInfo);
    databaseZone.query(condition).then((resultArray: BookInfo[]) => {
      resultArray.forEach((value) => {
        hilog.info(0x0000, 'cloudDb',
          `Succeeded in querying: bookName = ${value.bookName}    price: ${value.price?.toString()}`);
      });
    }).catch((err: BusinessError) => {
      hilog.error(0x0000, 'cloudDb', `Failed to query, code: ${err.code}, message: ${err.message}`);
    });

Condition-based Query

You can use multiple chained predicates to obtain desired objects. By default, multiple chained predicates are connected using the AND operation.

  1. Import required modules.

    import { cloudDatabase } from '@kit.CloudFoundationKit';
    import { BookInfo } from '../model/BookInfo';
    import { hilog } from '@kit.PerformanceAnalysisKit';
    import { BusinessError } from '@kit.BasicServicesKit';
  2. Query data based on specified conditions.

    • Construct query conditions: bookName is Jane Eyre. Then call the query() method to query books.

      let condition = new cloudDatabase.DatabaseQuery(BookInfo);
      
      condition.equalTo('bookName', 'Jane Eyre');
      databaseZone.query(condition).then((resultArray: BookInfo[]) => {
        resultArray.forEach((value) => {
          hilog.info(0x0000, 'cloudDb',
            `Succeeded in querying: bookName = ${value.bookName}    price: ${value.price?.toString()}`);
        });
      }).catch((err: BusinessError) => {
        hilog.error(0x0000, 'cloudDb', `Failed to query, code: ${err.code}, message: ${err.message}`);
      });
    • Construct query conditions: borrowerTime is 2025-09-01 18:00:00 000. Then call the query() method to query the data whose borrowing time is 2025-09-01 18:00:00 000.

      The Date field of the database object stores the local time. During query, the input parameter must be converted to the UTC time. Otherwise, the query result will be empty. For example, if the database stores 2025-09-01 18:00:00:000 (UTC+8), you need to use 2025-09-01 10:00:00:000 as the input parameter for query to correctly match the record.

      let condition = new cloudDatabase.DatabaseQuery(BookInfo);
          
      condition.equalTo('borrowerTime', '2025-09-01 10:00:00 000');
      databaseZone.query(condition).then((resultArray: BookInfo[]) => {
        resultArray.forEach((value) => {
          hilog.info(0x0000, 'cloudDb',
            `Succeeded in querying: bookName = ${value.bookName}    price: ${value.price?.toString()}`);
        });
      }).catch((err: BusinessError) => {
        hilog.error(0x0000, 'cloudDb', `Failed to query, code: ${err.code}, message: ${err.message}`);
      });
    • Construct query conditions: bookName is not Jane Eyre. Then call the query() method to query books.

      let condition = new cloudDatabase.DatabaseQuery(BookInfo);
      condition.notEqualTo('bookName', 'Jane Eyre');
      databaseZone.query(condition).then((resultArray: BookInfo[]) => {
        resultArray.forEach((value) => {
          hilog.info(0x0000, 'cloudDb',
            `Succeeded in querying: bookName = ${value.bookName}    price: ${value.price?.toString()}`);
        });
      }).catch((err: BusinessError) => {
        hilog.error(0x0000, 'cloudDb', `Failed to query, code: ${err.code}, message: ${err.message}`);
      });
    • Construct query conditions: bookName starts with Jane. Then call the query() method to query books.

      let condition = new cloudDatabase.DatabaseQuery(BookInfo);
      condition.beginsWith('bookName', 'Jane');
      databaseZone.query(condition).then((resultArray: BookInfo[]) => {
        resultArray.forEach((value) => {
          hilog.info(0x0000, 'cloudDb',
            `Succeeded in querying: bookName = ${value.bookName}    price: ${value.price?.toString()}`);
        });
      }).catch((err: BusinessError) => {
        hilog.error(0x0000, 'cloudDb', `Failed to query, code: ${err.code}, message: ${err.message}`);
      });
    • Construct query conditions: bookName ends with Eyre. Then call the query() method to query books.

      let condition = new cloudDatabase.DatabaseQuery(BookInfo);
      condition.endsWith('bookName', 'Eyre');
      databaseZone.query(condition).then((resultArray: BookInfo[]) => {
        resultArray.forEach((value) => {
          hilog.info(0x0000, 'cloudDb',
            `Succeeded in querying: bookName = ${value.bookName}    price: ${value.price?.toString()}`);
        });
      }).catch((err: BusinessError) => {
        hilog.error(0x0000, 'cloudDb', `Failed to query, code: ${err.code}, message: ${err.message}`);
      });
    • Construct query conditions: bookName contains d. Then call the query() method to query books.

      let condition = new cloudDatabase.DatabaseQuery(BookInfo);
      condition.contains('bookName', 'd');
      databaseZone.query(condition).then((resultArray: BookInfo[]) => {
        resultArray.forEach((value) => {
          hilog.info(0x0000, 'cloudDb',
            `Succeeded in querying: bookName = ${value.bookName}    price: ${value.price?.toString()}`);
        });
      }).catch((err: BusinessError) => {
        hilog.error(0x0000, 'cloudDb', `Failed to query, code: ${err.code}, message: ${err.message}`);
      });
    • Construct query conditions: price is greater than 82. Then call the query() method to query books.

      let condition = new cloudDatabase.DatabaseQuery(BookInfo);
      condition.greaterThan('price', 82.0);
      databaseZone.query(condition).then((resultArray: BookInfo[]) => {
        resultArray.forEach((value) => {
          hilog.info(0x0000, 'cloudDb',
            `Succeeded in querying: bookName = ${value.bookName}    price: ${value.price?.toString()}`);
        });
      }).catch((err: BusinessError) => {
        hilog.error(0x0000, 'cloudDb', `Failed to query, code: ${err.code}, message: ${err.message}`);
      });
    • Construct query conditions: price is lower than 82. Then call the query() method to query books.

      let condition = new cloudDatabase.DatabaseQuery(BookInfo);
      condition.lessThan('price', 82.0);
      databaseZone.query(condition).then((resultArray: BookInfo[]) => {
        resultArray.forEach((value) => {
          hilog.info(0x0000, 'cloudDb',
            `Succeeded in querying: bookName = ${value.bookName}    price: ${value.price?.toString()}`);
        });
      }).catch((err: BusinessError) => {
        hilog.error(0x0000, 'cloudDb', `Failed to query, code: ${err.code}, message: ${err.message}`);
      });
    • Construct query conditions: price is greater than or equal to 82. Then call the query() method to query books.

      let condition = new cloudDatabase.DatabaseQuery(BookInfo);
      condition.greaterThanOrEqualTo('price', 82.0);
      databaseZone.query(condition).then((resultArray: BookInfo[]) => {
        resultArray.forEach((value) => {
          hilog.info(0x0000, 'cloudDb',
            `Succeeded in querying: bookName = ${value.bookName}    price: ${value.price?.toString()}`);
        });
      }).catch((err: BusinessError) => {
        hilog.error(0x0000, 'cloudDb', `Failed to query, code: ${err.code}, message: ${err.message}`);
      });
    • Construct query conditions: price is lower than or equal to 82. Then call the query() method to query books.

      let condition = new cloudDatabase.DatabaseQuery(BookInfo);
      condition.lessThanOrEqualTo('price', 82.0);
      databaseZone.query(condition).then((resultArray: BookInfo[]) => {
        resultArray.forEach((value) => {
          hilog.info(0x0000, 'cloudDb',
            `Succeeded in querying: bookName = ${value.bookName}    price: ${value.price?.toString()}`);
        });
      }).catch((err: BusinessError) => {
        hilog.error(0x0000, 'cloudDb', `Failed to query, code: ${err.code}, message: ${err.message}`);
      });
    • Construct query conditions: bookName is contained in ['demo', 'Jane Eyre']. Then call the query() method to query books.

      let condition = new cloudDatabase.DatabaseQuery(BookInfo);
      condition.in('bookName', ['demo', 'Jane Eyre']);
      databaseZone.query(condition).then((resultArray: BookInfo[]) => {
        resultArray.forEach((value) => {
          hilog.info(0x0000, 'cloudDb',
            `Succeeded in querying: bookName = ${value.bookName}    price: ${value.price?.toString()}`);
        });
      }).catch((err: BusinessError) => {
        hilog.error(0x0000, 'cloudDb', `Failed to query, code: ${err.code}, message: ${err.message}`);
      });
    • Construct query conditions: price is empty. Then call the query() method to query books.

      let condition = new cloudDatabase.DatabaseQuery(BookInfo);
      condition.isNull('price');
      databaseZone.query(condition).then((resultArray: BookInfo[]) => {
        resultArray.forEach((value) => {
          hilog.info(0x0000, 'cloudDb',
            `Succeeded in querying: bookName = ${value.bookName}    price: ${value.price?.toString()}`);
        });
      }).catch((err: BusinessError) => {
        hilog.error(0x0000, 'cloudDb', `Failed to query, code: ${err.code}, message: ${err.message}`);
      });
    • Construct query conditions: price is not empty. Then call the query() method to query books.

      let condition = new cloudDatabase.DatabaseQuery(BookInfo);
      condition.isNotNull('price');
      databaseZone.query(condition).then((resultArray: BookInfo[]) => {
        resultArray.forEach((value) => {
          hilog.info(0x0000, 'cloudDb',
            `Succeeded in querying: bookName = ${value.bookName}    price: ${value.price?.toString()}`);
        });
      }).catch((err: BusinessError) => {
        hilog.error(0x0000, 'cloudDb', `Failed to query, code: ${err.code}, message: ${err.message}`);
      });
    • Construct query conditions: price is greater than 10 and lower than 50. Then call the query() method to query books.

      let condition = new cloudDatabase.DatabaseQuery(BookInfo);
      condition.beginGroup()
        .greaterThan('price', 10.0)
        .lessThan('price', 50.0)
        .endGroup();
      databaseZone.query(condition).then((resultArray: BookInfo[]) => {
        resultArray.forEach((value) => {
          hilog.info(0x0000, 'cloudDb',
            `Succeeded in querying: bookName = ${value.bookName}    price: ${value.price?.toString()}`);
        });
      }).catch((err: BusinessError) => {
        hilog.error(0x0000, 'cloudDb', `Failed to query, code: ${err.code}, message: ${err.message}`);
      });
    • Call the query() method to query books sorted by price in ascending order.

      let condition = new cloudDatabase.DatabaseQuery(BookInfo);
      condition.orderByAsc('price');
      databaseZone.query(condition).then((resultArray: BookInfo[]) => {
        resultArray.forEach((value) => {
          hilog.info(0x0000, 'cloudDb',
            `Succeeded in querying: bookName = ${value.bookName}    price: ${value.price?.toString()}`);
        });
      }).catch((err: BusinessError) => {
        hilog.error(0x0000, 'cloudDb', `Failed to query, code: ${err.code}, message: ${err.message}`);
      });
    • Construct query conditions: price is lower than or equal to 50. Then call the query() method to query books sorted by price in descending order.

      let condition = new cloudDatabase.DatabaseQuery(BookInfo);
      condition.lessThan('price', 50.0).orderByDesc('price');
      databaseZone.query(condition).then((resultArray: BookInfo[]) => {
        resultArray.forEach((value) => {
          hilog.info(0x0000, 'cloudDb',
            `Succeeded in querying: bookName = ${value.bookName}    price: ${value.price?.toString()}`);
        });
      }).catch((err: BusinessError) => {
        hilog.error(0x0000, 'cloudDb', `Failed to query, code: ${err.code}, message: ${err.message}`);
      });
    • Construct query conditions: price is lower than 50 or bookName is demo. Then call the query() method to query books.

      let condition = new cloudDatabase.DatabaseQuery(BookInfo);
      condition.lessThan('price', 50.0).or().equalTo('bookName', 'demo');
      databaseZone.query(condition).then((resultArray: BookInfo[]) => {
        resultArray.forEach((value) => {
          hilog.info(0x0000, 'cloudDb',
            `Succeeded in querying: bookName = ${value.bookName}    price: ${value.price?.toString()}`);
        });
      }).catch((err: BusinessError) => {
        hilog.error(0x0000, 'cloudDb', `Failed to query, code: ${err.code}, message: ${err.message}`);
      });
    • Construct query conditions: price is greater than 40 and bookName contains j. Then call the query() method to query books.

      let condition = new cloudDatabase.DatabaseQuery(BookInfo);
      condition.greaterThan('price', 40.0).and().contains('bookName', 'j');
      databaseZone.query(condition).then((resultArray: BookInfo[]) => {
        resultArray.forEach((value) => {
          hilog.info(0x0000, 'cloudDb',
            `Succeeded in querying: bookName = ${value.bookName}    price: ${value.price?.toString()}`);
        });
      }).catch((err: BusinessError) => {
        hilog.error(0x0000, 'cloudDb', `Failed to query, code: ${err.code}, message: ${err.message}`);
      });
    • Construct query conditions: price is lower than or equal to 50. Then call the query() method to query books sorted by price in descending order, with a maximum of two results returned.

      let condition = new cloudDatabase.DatabaseQuery(BookInfo);
      condition.lessThan('price', 50.0).orderByDesc('price').limit(2, 0);
      databaseZone.query(condition).then((resultArray: BookInfo[]) => {
        resultArray.forEach((value) => {
          hilog.info(0x0000, 'cloudDb',
            `Succeeded in querying: bookName = ${value.bookName}    price: ${value.price?.toString()}`);
        });
      }).catch((err: BusinessError) => {
        hilog.error(0x0000, 'cloudDb', `Failed to query, code: ${err.code}, message: ${err.message}`);
      });

Performing Calculations on the Query Result

  1. Import required modules.

    import { cloudDatabase } from '@kit.CloudFoundationKit';
    import { BookInfo } from '../model/BookInfo';
    import { hilog } from '@kit.PerformanceAnalysisKit';
    import { BusinessError } from '@kit.BasicServicesKit';
  2. You can use calculateQuery() to perform arithmetic calculations on a field in the query result object and return the calculation result.

    let condition = new cloudDatabase.DatabaseQuery(BookInfo);
    condition.lessThan('price', 50.0);
    databaseZone.calculateQuery(condition, 'price', cloudDatabase.QueryCalculate.AVERAGE).then((num: number) => {
      hilog.info(0x0000, 'cloudDb', `Succeeded in querying: QueryCalculate.AVERAGE price  = ${num}`);
    }).catch((err: BusinessError) => {
      hilog.error(0x0000, 'cloudDb', `Failed to query, code: ${err.code}, message: ${err.message}`);
    });

Random Query

From version 6.0.1(21), the random query function is supported.

  1. Import required modules.

    import { cloudDatabase } from '@kit.CloudFoundationKit';
    import { BookInfo } from '../model/BookInfo';
    import { hilog } from '@kit.PerformanceAnalysisKit';
    import { BusinessError } from '@kit.BasicServicesKit';
  2. You can use orderByRandom() to display objects in the query result set in random order.

    This method applies to scenarios such as recommending random content or playing random audio and video.

    let condition = new cloudDatabase.DatabaseQuery(BookInfo);
    condition.orderByRandom().limit(10);
    databaseZone.query(condition).then((resultArray: BookInfo[]) => {
      resultArray.forEach((value) => {
        hilog.info(0x0000, 'cloudDb',
          `Succeeded in querying: bookName = ${value.bookName}    price: ${value.price?.toString()}`);
      });
    }).catch((err: BusinessError) => {
      hilog.error(0x0000, 'cloudDb', `Failed to query, code: ${err.code}, message: ${err.message}`);
    });