We use essential cookies for the website to function, as well as analytics cookies for analyzing and creating statistics of the website performance. To agree to the use of analytics cookies, click "Accept All". You can manage your preferences at any time by clicking "Cookie Settings" on the footer. More Information.

Only Essential Cookies
Accept All
GuidesApplication ServicesCloud Foundation KitCloud DBQuerying Data

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.

NOTE
  • 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.

  • Query all data of the BookInfo object type.

    Collapse
    Word wrap
    Dark theme
    Copy code
    1. import { hilog } from '@kit.PerformanceAnalysisKit';
    2. async queryAll() {
    3. try {
    4. let resultArray = await databaseZone.query(condition);
    5. hilog.info(0x0000, 'testTag', `Succeeded in querying data, result: ${JSON.stringify(resultArray)}`);
    6. } catch (err) {
    7. hilog.error(0x0000, 'testTag', `Failed to query data, code: ${err.code}, message: ${err.message}`);
    8. }
    9. }
    NOTE

    In the future, HiLog needs to be imported from @kit.PerformanceAnalysisKit, and this will not be shown in the sample code.

  • Asynchronously query books with the specified bookName.

    Collapse
    Word wrap
    Dark theme
    Copy code
    1. async queryBook(bookName: string): Promise<BookInfo> {
    2. try {
    3. condition.equalTo('bookName', bookName);
    4. let resultArray = await databaseZone.query(condition);
    5. let bookInfo = resultArray[0];
    6. hilog.info(0x0000, 'testTag', `Succeeded in querying data, result: ${JSON.stringify(resultArray)}`);
    7. return Promise.resolve(bookInfo);
    8. } catch (err) {
    9. hilog.error(0x0000, 'testTag', `Failed to query data, code: ${err.code}, message: ${err.message}`);
    10. return Promise.reject(err);
    11. }
    12. }

Compound Query

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

  • Construct query conditions: bookName contains Database and price is higher than 20.0 and lower than 50.0. Then call the query() method to query books.

    Collapse
    Word wrap
    Dark theme
    Copy code
    1. condition.contains('bookName', 'Database')
    2. .greaterThan('price', 20.0)
    3. .and()
    4. .lessThan('price', 50.0);
    5. let resultArray = await databaseZone.query(condition);
  • Construct query conditions: bookName contains Database and price is lower than 20.0 or higher than 50.0. Then call the query() method to query books.

    Collapse
    Word wrap
    Dark theme
    Copy code
    1. condition.contains('bookName', 'Database')
    2. .lessThan('price', 20.0)
    3. .or()
    4. .greaterThan('price', 50.0);
    5. let resultArray = await databaseZone.query(condition);
  • Construct query conditions: bookName contains A Tale of Two Cities, author is Charles Dickens, and price is higher than 60.0. Then call the query() method to query books.

    Collapse
    Word wrap
    Dark theme
    Copy code
    1. condition.contains('bookName', 'A Tale of Two Cities')
    2. .equalTo('author', 'Charles Dickens')
    3. .greaterThan('price', 60.0);
    4. let resultArray = await databaseZone.query(condition);
  • Construct query conditions: bookName contains Autobiography, author is William Shakespeare or Charles Dickens, and price is higher than 60.0. Then call the query() method to query books.

    Collapse
    Word wrap
    Dark theme
    Copy code
    1. condition.contains('bookName', 'Autobiography')
    2. .beginGroup()
    3. .equalTo('author', 'William Shakespeare')
    4. .or()
    5. .equalTo('author', 'Charles Dickens')
    6. .endGroup()
    7. .greaterThan('price', 60.0);
    8. let resultArray = await databaseZone.query(condition);
  • Construct query conditions: bookName contains Database and borrowerTime is within a specified period. Then call the query() method to query books. When building query conditions for Date-type fields (for example, when using greaterThan(), greaterThanOrEqualTo(), lessThan(), lessThanOrEqualTo(), equalTo(), or notEqualTo()), you need to call the getTime() method to convert the Date object into a number.

    Collapse
    Word wrap
    Dark theme
    Copy code
    1. let begin = (new Date("2025-12-29T08:00:00.000+08:00")).getTime();
    2. let end = (new Date("2025-12-31T08:00:00.000+08:00")).getTime();
    3. condition.contains('bookName', 'Database')
    4. .greaterThan('borrowerTime', begin)
    5. .and()
    6. .lessThan('borrowerTime', end);
    7. let resultArray = await databaseZone.query(condition);

Sorting Data

You can use orderByAsc() or orderByDesc() to sort the objects in the query result set in ascending or descending order by a certain field. The sorting predicate must be placed after other query predicates and before the predicate that limits the number of returned query results.

Collapse
Word wrap
Dark theme
Copy code
  1. condition.lessThan('price', 50.0)
  2. .orderByDesc('price');
  3. let resultArray = await databaseZone.query(condition);

Random Query

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

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.

Collapse
Word wrap
Dark theme
Copy code
  1. condition.orderByRandom()
  2. .limit(10);
  3. let resultArray = await databaseZone.query(condition);

Limiting the Number of Returned Query Results

During data query, you can use limit() to limit the start position and number of query results to be returned, implementing data pagination. For example, use it together with the sorting query predicate to obtain top N data records.

To limit the number of returned query results, the limiting predicate should be placed after all other predicates.

  • Construct query conditions and call the query() method. Here, books cheaper than 50.0 are queried, and only the first 10 records are displayed.

    Collapse
    Word wrap
    Dark theme
    Copy code
    1. condition.lessThan('price', 50.0)
    2. .limit(10);
    3. let resultArray = await databaseZone.query(condition);
  • Construct query conditions, call the query() method to query books, and sort the query results in descending order of price. Here, books cheaper than 50.0 are queried, and only 10 records from the sixth record are displayed.

    Collapse
    Word wrap
    Dark theme
    Copy code
    1. condition.lessThan('price', 50.0)
    2. .orderByDesc('price')
    3. .limit(10, 6);
    4. let resultArray = await databaseZone.query(condition);

Performing Calculations on the Query Result

When querying data, you can use calculateQuery() to perform arithmetic calculation on a field in the query result object and return the calculation result.

Construct query conditions and call the calculateQuery() method to query all books cheaper than 50.0 and calculate the average price of these books.

Collapse
Word wrap
Dark theme
Copy code
  1. async calculateQuery() {
  2. try {
  3. condition.lessThan('price', 50.0);
  4. let resultNum = await databaseZone.calculateQuery(condition, 'price', cloudDatabase.QueryCalculate.AVERAGE);
  5. hilog.info(0x0000, 'testTag', `Succeeded in calculating queried data, result: ${JSON.stringify(resultNum)}`);
  6. } catch (err) {
  7. hilog.error(0x0000, 'testTag', `Failed to calculate queried data, code: ${err.code}, message: ${err.message}`);
  8. }
  9. }
Search in Guides
Enter a keyword.