请在云函数中使用
// 云函数入口文件
const cloud = require(‘wx-server-sdk’)
cloud.init()
const db = cloud.database({
env: ‘环境ID’
})
const _ = db.command
const $ = db.command.aggregate
// 云函数入口函数
exports.main = async(event, context) => {
let table = ‘集合名称’
return db.collection(table).aggregate()
.addFields({
match: $.eq([‘$type’, ‘type1’])
})
.match({
match: !0
})
.sample({
size: 1 // 随机取一条type=type1的记录
})
.group({
_id: ‘any’,
type1Row: $.push(‘$$ROOT’)
})
.lookup({
from: table,
pipeline: $.pipeline()
.addFields({
match: $.eq([‘$type’, ‘type2’])
})
.match({
match: !0
})
.sample({
size: 1 // 随机取一条type=type2的记录
})
.done(),
as: ‘type2Row’,
})
.addFields({
allRows: $.concatArrays([‘$type1Row’, ‘$type2Row’])
})
.unwind(‘$allRows’)
.replaceRoot({
newRoot: ‘$allRows’
})
.end()
}