005 WeChat Mini Program Cloud Development API Database-Query Records-Aggregation-Statistical Number of Records

Insert image description here

1. WeChat Mini Program Cloud Development API Database-Query Records

WeChat Mini Program Cloud Development API Database is a convenient and fast database solution that allows developers to directly use cloud database functions in Mini Programs without having to build and manage servers themselves. In the WeChat Mini Program Cloud Development API database, we can query specified records to obtain relevant data and information. This article will introduce in detail the query and recording method of WeChat applet cloud development API database through cases and code.

  • Open cloud development environment

    Before using cloud development, you need to open a cloud development environment. Log in to the WeChat public platform, enter the "Development" -> "Cloud Development" page, and follow the prompts to complete the activation.

  • Create a cloud development environment

    cloudfunctionsAfter activating the cloud development environment, you need to create a folder named in the root directory of the mini program to store cloud functions. Create a folder named under cloudfunctionsthe folder queryRecordsto store cloud functions that query records.

  • Initialize the cloud development environment

    Create a file named under queryRecordsthe folder initCloudBase.jsto initialize the cloud development environment. The contents of the file are as follows:

// 初始化云开发环境
wx.cloud.init({
    
    
  env: 'your-cloud-env-id' // 替换为你的云开发环境的 ID
})    
  • Create a cloud function

    Create a file named under queryRecordsthe folder queryRecords.jsfor writing cloud functions. The contents of the file are as follows:

// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()

// 查询记录的云函数
exports.main = async (event, context) => {
    
    
  const db = cloud.database()
  try {
    
    
    const result = await db.collection('todos').get() // 根据传入的条件查询记录(可选)
    if (result.data.length === 0) {
    
     // 如果查询结果为空,返回提示信息(可选)
      return 'No records found.'
    } else {
    
     // 如果查询结果不为空,返回查询结果(必选)
      return result.data[0] // 仅返回第一条记录(根据实际需求修改)
    }
  } catch (e) {
    
     // 打印错误信息并抛出异常(必选)
    console.error(e)
    throw e
  } finally {
    
     // 关闭云开发环境,释放资源(可选)
    cloud.database().collection('todos').doc('recordId').get().then(res => {
    
     // 根据查询条件查找并获取记录(可选)
      if (res.data && res.data.title) {
    
     // 如果找到记录,返回记录数据(可选)
        return res.data // 仅返回第一条记录(根据实际需求修改)
      } else {
    
     // 如果未找到记录,返回 null(可选)
        return null
      }
    }).catch(err => {
    
     // 处理异常情况(可选)
      console.error('Error checking record status:', err) // 打印检查记录状态时出现的错误信息(可以根据实际需求修改提示信息)
    })
    cloud.close() // 关闭云开发环境,释放资源(可选)
  }
}

Case code

Suppose we have a WeChat applet for managing users' shopping lists. Users can use the search function to find specific shopping list records. In order to realize this function, we need to use the query and record method of the WeChat applet cloud development API database.

Code description

  1. In the WeChat applet, we need to introduce relevant libraries and components. Add the following code in the app.json file:
{
    
      
  "usingComponents": {
    
      
    "cloud-native": "/path/to/cloud-native"  
  }  
}

Among them, "/path/to/cloud-native" is the path of the cloud development component.

  1. In the page where records need to be queried, the cloud development database component is introduced. Add the following code to the corresponding .wxml file:
html复制代码

<cloud-native-database:bind id="bindData" dbname="{
     
     {dbname}}" collection="{
     
     {collection}}" key="{
     
     {key}}" />

Among them, { {dbname}}, { {collection}} and { {key}} are the corresponding data source names, collection names and key names, which can be modified according to actual needs.

  1. In the page where records need to be queried, write the logic for querying records. Add the following code to the corresponding .js file:
// 获取云开发数据库组件实例  
const bindData = wx.cloud.database().collection('bind')  
// 定义查询条件  
const query = {
    
     name: '商品1' }  
// 调用 get 方法查询记录  
bindData.get(query).then(res => {
    
      
  // 处理查询结果  
  console.log(res)  
})

In the above code, we first obtain the instance of the cloud development database through the wx.cloud.database() method, then specify the collection name through the collection() method, and specify the key name through the doc() method. Next, we define a query condition object query, which contains the query conditions for the records to be queried. Finally, we use the get() method to query records that meet the conditions. The get() method returns a Promise object, and we can use the then() method to process the query results. In the case, we output the query results to the console.

Note: Querying records may return multiple results, which we can process as needed. In addition, querying records may consume a certain amount of time and resources, which needs to be weighed based on the actual situation.

2. WeChat Mini Program Cloud Development API Database-Aggregation

WeChat Mini Program Cloud Development API Database is a powerful database solution that provides many convenient and fast database operation methods. Among them, aggregation operation is a commonly used data processing method, which can perform statistics, analysis and calculation on data in the database. This article will introduce in detail the aggregation operation method of WeChat applet cloud development API database through cases and code.

  • Open cloud development environment

    Before using cloud development, you need to open a cloud development environment. Log in to the WeChat public platform, enter the "Development" -> "Cloud Development" page, and follow the prompts to complete the activation.

  • Create a cloud development environment

    cloudfunctionsAfter activating the cloud development environment, you need to create a folder named in the root directory of the mini program to store cloud functions. Create a folder named under cloudfunctionsthe folder aggregateRecordsto store cloud functions that aggregate records.

  • Initialize the cloud development environment

    Create a file named under aggregateRecordsthe folder initCloudBase.jsto initialize the cloud development environment. The contents of the file are as follows:

// 初始化云开发环境
wx.cloud.init({
    
    
  env: 'your-cloud-env-id' // 替换为你的云开发环境的 ID
})
  • Create a cloud function

    Create a file named under aggregateRecordsthe folder aggregateRecords.jsfor writing cloud functions. The contents of the file are as follows:

// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()

// 聚合记录的云函数
exports.main = async (event, context) => {
    
    
  const db = cloud.database()
  try {
    
    
    // 根据传入的条件进行聚合查询(必选)
    const result = await db.collection('todos').aggregate() // 默认聚合所有文档并返回一个包含所有聚合结果的数组
    if (result.length === 0) {
    
     // 如果查询结果为空,返回提示信息(可选)
      return 'No records found.'
    } else {
    
     // 如果查询结果不为空,返回查询结果(必选)
      return result[0]._id // 仅返回第一条记录的 ID(根据实际需求修改)
    }
  } catch (e) {
    
     // 打印错误信息并抛出异常(必选)
    console.error(e)
    throw e
  } finally {
    
     // 关闭云开发环境,释放资源(可选)
    cloud.database().collection('todos').doc('recordId').get().then(res => {
    
     // 根据查询条件查找并获取记录(可选)
      if (res.data && res.data.title) {
    
     // 如果找到记录,返回记录数据(可选)
        return res.data // 仅返回第一条记录(根据实际需求修改)
      } else {
    
     // 如果未找到记录,返回 null(可选)
        return null
      }
    }).catch(err => {
    
     // 处理异常情况(可选)
      console.error('Error checking record status:', err) // 打印检查记录状态时出现的错误信息(可以根据实际需求修改提示信息)
    })
    cloud.close() // 关闭云开发环境,释放资源(可选)
  }
}

Case code

Suppose we have a WeChat applet for managing users' shopping lists. We hope to count the total amount of goods purchased by users in order to recommend higher-priced goods to users or provide other services. In order to realize this function, we need to use the aggregation operation method of the WeChat applet cloud development API database.

Code description

  1. In the WeChat applet, we need to introduce relevant libraries and components. Add the following code in the app.json file:
{
    
      
  "usingComponents": {
    
      
    "cloud-native": "/path/to/cloud-native"  
  }  
}

Among them, "/path/to/cloud-native" is the path of the cloud development component.

  1. Introduce cloud development database components into pages that require aggregation operations. Add the following code to the corresponding .wxml file:
html复制代码

<cloud-native-database:bind id="bindData" dbname="{
     
     {dbname}}" collection="{
     
     {collection}}" key="{
     
     {key}}" />

Among them, { {dbname}}, { {collection}} and { {key}} are the corresponding data source names, collection names and key names, which can be modified according to actual needs.

  1. In the page that requires aggregation operation, write the logic of aggregation operation. Add the following code to the corresponding .js file:
// 获取云开发数据库组件实例  
const bindData = wx.cloud.database().collection('bind')  
// 定义聚合操作的计算方法  
const getTotalPrice = doc => {
    
      
  return doc.price * doc.quantity  
}  
// 调用 aggregate 方法进行聚合操作  
bindData.aggregate()  
  .match({
    
     price: {
    
     $gt: 0 } }) // 筛选价格大于0的记录  
  .groupBy({
    
     field: 'user_id', as: 'user_total_price' }) // 根据用户ID分组,计算每个用户的总金额  
  .sum('price', 'quantity', 'user_total_price') // 对每个分组的总金额进行求和操作  
  .exec((err, result) => {
    
      
    if (err) {
    
      
      console.error(err)  
      return  
    }  
    console.log(result) // 打印聚合结果  
  })

In the above code, we first obtain the instance of the cloud development database through the wx.cloud.database() method, then specify the collection name through the collection() method, and specify the key name through the doc() method. Next, we define an aggregation operation calculation method getTotalPrice, which receives a document object as a parameter and returns the amount of the document. Then, we use the aggregate() method to start the aggregation operation. In the aggregation operation, we use the match() method to filter records with a price greater than 0, use the groupBy() method to group based on user ID, and use the sum() method to sum the total amount of each group. Finally, we use the exec() method to perform the aggregation operation and process the returned results. In the case we print the results to the console.

Note: The aggregation operation may consume a lot of time and resources and needs to be optimized and adjusted according to the actual situation. In addition, you need to pay attention to the correctness and security of the data when processing aggregation results.

3. WeChat Mini Program Cloud Development API Database-Number of Statistical Records

WeChat Mini Program Cloud Development API Database is a convenient and fast database solution that allows developers to directly use cloud database functions in Mini Programs without having to build and manage servers themselves. In the WeChat Mini Program Cloud Development API database, we can count the number of records under specified conditions to understand the distribution and scale of data in the database. This article will introduce in detail the method of counting the number of records in the WeChat applet cloud development API database through cases and code.

  • Open cloud development environment

    Before using cloud development, you need to open a cloud development environment. Log in to the WeChat public platform, enter the "Development" -> "Cloud Development" page, and follow the prompts to complete the activation.

  • Create a cloud development environment

    cloudfunctionsAfter activating the cloud development environment, you need to create a folder named in the root directory of the mini program to store cloud functions. Create a folder named under the folder to store the cloud function that counts the number of records cloudfunctions.countRecords

  • Initialize the cloud development environment

    Create a file named under countRecordsthe folder initCloudBase.jsto initialize the cloud development environment. The contents of the file are as follows:

// 初始化云开发环境
wx.cloud.init({
    
    
  env: 'your-cloud-env-id' // 替换为你的云开发环境的 ID
})    
  • Create a cloud function

    Create a file named under countRecordsthe folder countRecords.jsfor writing cloud functions. The contents of the file are as follows:

// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()

// 统计记录数量的云函数
exports.main = async (event, context) => {
    
    
  const db = cloud.database()
  try {
    
    
    // 根据传入的条件查询记录数量(必选)
    const result = await db.collection('todos').count() // 默认返回集合中文档的数量(即记录数量)
    if (result > 0) {
    
     // 如果查询结果大于 0,返回记录数量(可选)
      return result // 仅返回第一条记录的 ID(根据实际需求修改)
    } else {
    
     // 如果查询结果小于等于 0,返回提示信息(可选)
      return 'No records found.'
    }
  } catch (e) {
    
     // 打印错误信息并抛出异常(必选)
    console.error(e)
    throw e
  } finally {
    
     // 关闭云开发环境,释放资源(可选)
    cloud.database().collection('todos').doc('recordId').get().then(res => {
    
     // 根据查询条件查找并获取记录(可选)
      if (res.data && res.data.title) {
    
     // 如果找到记录,返回记录数据(可选)
        return res.data // 仅返回第一条记录(根据实际需求修改)
      } else {
    
     // 如果未找到记录,返回 null(可选)
        return null
      }
    }).catch(err => {
    
     // 处理异常情况(可选)
      console.error('Error checking record status:', err) // 打印检查记录状态时出现的错误信息(可以根据实际需求修改提示信息)
    })
    cloud.close() // 关闭云开发环境,释放资源(可选)
  }
}

Case code

Suppose we have a WeChat applet for managing users' shopping lists. We want to count the number of items in a shopping list collection to understand user shopping preferences and trends. In order to realize this function, we need to use the statistical record number method of the WeChat applet cloud development API database.

Code description

  1. In the WeChat applet, we need to introduce relevant libraries and components. Add the following code in the app.json file:
{
    
      
  "usingComponents": {
    
      
    "cloud-native": "/path/to/cloud-native"  
  }  
}

Among them, "/path/to/cloud-native" is the path of the cloud development component.

  1. Introduce the cloud development database component into the page where the number of records needs to be counted. Add the following code to the corresponding .wxml file:
html复制代码

<cloud-native-database:bind id="bindData" dbname="{
     
     {dbname}}" collection="{
     
     {collection}}" key="{
     
     {key}}" />

Among them, { {dbname}}, { {collection}} and { {key}} are the corresponding data source names, collection names and key names, which can be modified according to actual needs.

  1. In the page where the number of records needs to be counted, write the logic to count the number of records. Add the following code to the corresponding .js file:
// 获取云开发数据库组件实例  
const bindData = wx.cloud.database().collection('bind')  
// 定义查询条件  
const query = {
    
    } // 查询所有记录  
// 调用 count 方法统计记录数量  
bindData.count(query).then(res => {
    
      
  // 处理统计结果  
  console.log(res)  
})

In the above code, we first obtain the instance of the cloud development database through the wx.cloud.database() method, then specify the collection name through the collection() method, and specify the key name through the doc() method. Next, we defined an empty object query to query all records. Finally, we use the count() method to count the number of records and return a Promise object. In the case, we output the statistical results to the console.

Note: Statistics of the number of records may consume a certain amount of time and resources, and need to be optimized and adjusted according to the actual situation. In addition, you need to pay attention to the correctness and security of the data when processing statistical results.

Guess you like

Origin blog.csdn.net/u014096024/article/details/132774092