当前位置:网站首页>Applet cloud development joint table data query and application in cloud function
Applet cloud development joint table data query and application in cloud function
2022-06-25 09:28:00 【Maoningyi】
Click to watch the video ↓↓↓
Applet cloud development joint table data query and application in cloud functions | Multi-table query | Even the table lookup | Aggregate functions
List of articles
Hello everyone , I'm Ning Yi , Today, let's learn how to query the join table data of cloud development , And teach you how to apply cloud functions , Print the results of our query in the wechat developer tool
Let's set the scene first , Now there are two tables , Let's check the average scores of all the students in the class Mr. Xu took 
1、 League table query
Let's first look at how to query , The data connecting the two tables is class In the table id and student In the table class_id
So we should first find out what teacher Xu's class is id, yes 2, And then check student In the table class_id by 2 Of the students , Zhang Er and Li Er , Calculate the average score of the two students
Let's take a look at how to implement such a joint table query in cloud development
You should learn to read cloud development documents as much as possible , However, this document is actually very difficult for novices , If you have any functions that you want me to demonstrate, you can tell me in the bullet screen or comments , If there are many people who want to see , I will issue a separate issue to talk about .
Cloud development documentation , In the development guide – In the database , There is an introduction to join table query , We use lookup Function to realize joint table query
lookup({
from: < The name of the collection to connect >,
localField: < Enter the fields of the record to match equally >,
foreignField: < The fields of the connected set to be matched equally >,
as: < Output array field name >
})
(1)lookup Join two tables
Apply to the scenario we set above , It's like this , Need to call end Method to mark the end of the definition
lookup({
from: 'student', // Table to associate student
localField: 'id', //class Associated fields in the table
foreignField: 'class_id', //student Associated fields in the table
as: 'stu' // Defines the alias of the output array
})
.end()
This statement will find the following results , Will find out the information of the class and the information of all the students corresponding to the class
{
"list":
[{
"id":1,
"teacher":" Teacher wang ",
"cname":" Class one ",
"stu":[
{
"sname":" Ning Yi ",
"class_id":1,
"score":90
}
]
},
{
"id":2,
"teacher":" Miss Xu ",
"cname":" Class two ",
"stu":[
{
"class_id":2,
"sname":" Zhang Er ",
"score":100
},
{
"class_id":2,
"sname":" Li Er ",
"score":80
}
]
}]
}
But we only need the data of the students in Mr. Xu's class , So we need to add where Conditions , stay lookup You can't follow it directly where, Need to use match Instead of . Let's improve the above code
(2) Use match Query conditions
.lookup({
from: 'student',
localField: 'id',
foreignField: 'class_id',
as: 'stu'
})
.match({
teacher:" Miss Xu "
})
.end()
Now we just return the student data of Mr. Xu's class , Student data is in stu In the corresponding array
{
"list":
[
{
"_id":"5e847ab25eb9428600a512352fa6c7c4",
"id":2,
"teacher":" Miss Xu ",
"cname":" Class two ",
// Student data
"stu":[
{
"_id":"37e26adb5eb945a70084351e57f6d717",
"class_id":2,
"sname":" Zhang Er ",
"score":100
},
{
"_id":"5e847ab25eb945cf00a5884204297ed8",
"class_id":2,
"sname":" Li Er ",
"score":80
}
]
}
]
}
Next, let's continue to optimize the code , Returns the student's average score directly
(3) Return the average student grade directly
If you want to be in a connected table ( In this course student) Do aggregate operations , Just use pipeline Method
however pipeline Cannot be associated with localField、foreignField share , So let's delete localField、foreignField And then pipeline Get student grades in (score) Average value
.lookup({
from: 'student',
pipeline: $.pipeline()
.group({
_id: null,
score: $.avg('$score')
})
.done(),
as: 'stu'
})
.match({
teacher:" Miss Xu "
})
.end()
Now the printed data is like this
{
"list":
[
{
"_id":"5e847ab25eb9428600a512352fa6c7c4",
"id":2,
"teacher":" Miss Xu ",
"cname":" Class two ",
"stu":[
{
"_id":null,
"score":90
}
]
}
]
}
But now the output data is a little complicated , If you just want to show teacher and score These two values , Let's do the following
(4) Display only teacher and score These two values
.lookup({
from: 'student',
pipeline: $.pipeline()
.group({
_id: null,
score: $.avg('$score')
})
.done(),
as: 'stu'
})
.match({
teacher:" Miss Xu "
})
.replaceRoot({
newRoot: $.mergeObjects([$.arrayElemAt(['$stu', 0]), '$$ROOT'])
})
.project({
_id:0,
teacher:1,
score:1
})
.end()
Now the printed data is like this
{
"list":
[
{
"score":90,"teacher":" Miss Xu "}
]
}
replaceRoot({ newRoot: < expression > }) It's fixed writing , Output the existing field as a new node , We usually use it to turn a two-level array into a one-level array
mergeObjects Is the accumulator operator ,$.arrayElemAt(['$stu', 0]), '$$ROOT’] Will be stu First element in array , That is to say [{"_id":null,"score":90}] Merge to the following nodes of the array , That is to say, with teacher、cname These fields are the same level
project There will be _id Set later as 0, Set the element we want to display to 1, You can control the last output field
2、 Application in cloud function
Next, let's look at how to use cloud functions , Print the above query results in the wechat developer tool
(1) Add data to the cloud database
We open the cloud development console in the wechat developer tool , First create these two tables in the cloud database , Let's create class Table as an example 
After creating the form , Let's add records to the table , Add... According to the data in the table above , The data of class 2 is added below 
After all the data has been added , Go to the wechat developer tool cloud functions folder and create a folder named test The cloud function of
We created the cloud development project in advance , If you don't know how to create , You can see what I sent before 30 Minutes to create and launch the course of cloud development applet , It teaches you how to create
(2) Create a cloud function and initialize the database
After creation , The system will help us create a test Folder , We turn on test/index.js file , Delete some code created by default , And initialize the database , Like this
// Cloud function entry file
const cloud = require('wx-server-sdk')
cloud.init()
// Initialize database
const db = cloud.database()
const _ = db.command
const $ = _.aggregate
// Cloud function entry function
exports.main = async (event, context) => {
// Let's continue to add code here
}
(3) Edit cloud function entry function
// Cloud function entry function
exports.main = async (event, context) => {
return await db.collection('class').aggregate()
.lookup({
from: 'student',
pipeline: $.pipeline()
.group({
_id: null,
score: $.avg('$score')
})
.done(),
as: 'stu'
})
.match({
teacher:" Miss Xu "
})
.replaceRoot({
newRoot: $.mergeObjects([$.arrayElemAt(['$stu', 0]), '$$ROOT'])
})
.project({
_id:0,
teacher:1,
score:1
})
.end()
}
Save the file after editing , And upload and deploy cloud functions
(4) Upload and deploy cloud functions
Right click the cloud function , Select upload and deploy : Cloud installation depends on ( Do not upload node_modules)
Open the cloud development console — Click cloud function – find test Cloud function click cloud test 
In the pop-up test box , Click the run test button directly 
The returned results will be printed below , This indicates that the associated table query has been successful 
边栏推荐
- C#启动程序传递参数丢失双引号,如何解决?
- Socket programming -- epoll model
- Is it safe to open an account on the compass?
- (translation) the use of letter spacing to improve the readability of all capital text
- How to delete a blank page that cannot be deleted in word
- Lvs-dr mode single network segment case
- Oracle-单行函数大全
- Webgl Google prompt memory out of bounds (runtimeerror:memory access out of bounds, Firefox prompt index out of bounds)
- 五、项目实战---识别人和马
- Socket programming -- poll model
猜你喜欢

With the QQ group file storage function of super nice, you immediately have n cloud disks that are easy to download and never expire

sklearn PolynomialFeatures的具体用法

TLAB mechanism of JVM object memory allocation and TLAB process in G1

Study on correlation of pumpkin price and design of price prediction model based on BP neural network

自定义注解之编译时注解(RetentionPolicy.CLASS)

将jar包注册为服务,实现开机自动启动

Analysis on the thinking of 2022 meisai C question

【期末复习笔记】数字逻辑
![[competition - Rural Revitalization] experience sharing of Zhejiang Rural Revitalization creative competition](/img/b4/84c30ed112c4dffd8d51697b2f4a4f.jpg)
[competition - Rural Revitalization] experience sharing of Zhejiang Rural Revitalization creative competition

3大问题!Redis缓存异常及处理方案总结
随机推荐
Voiceprint Technology (II): Fundamentals of audio signal processing
Notes on key words in the original English work biography of jobs (IV) [chapter two]
C # startup program loses double quotation marks for parameters passed. How to solve it?
[zufe school competition] difficulty classification and competition suggestions of common competitions in the school (taking Zhejiang University of Finance and economics as an example)
Level 6 easy to mix words
Notes on key vocabulary of the original English work biography of jobs (I) [introduction]
Cazy eight trigrams maze of Chang'an campaign
flutter 多语言的intl: ^0.17.0导不进去
[zufe expense reimbursement] zhecai invoice reimbursement specification (taking Xinmiao reimbursement as an example), which can be passed in one trip at most
Japanese online notes for postgraduate entrance examination (9): composition template
2022 postgraduate entrance examination experience post -- Alibaba Business School of Hangzhou Normal University -- management science and Engineering (including the recommendation of books and course
Socket programming -- poll model
nodejs 使用Express框架demo
SQL高级
How annotation lib and processor lib reference
CSV parameterization in JMeter
【期末复习笔记】数字逻辑
使用Navicat对比多环境数据库数据差异和结构差异,以及自动DML和DDL脚本
203 postgraduate entrance examination Japanese self-study postgraduate entrance examination experience post; Can I learn Japanese by myself?
Is it safe to open an account at Huatai Securities?