云函数从一个集合中条件查询随机?
发布于 6 年前 作者 fanyang 10846 次浏览 来自 官方Issues
table: {
  {
    _id:123132,
    type:"type1"
    msg:""
  },{
    _id:123154,
    type:"type1"
    msg:""
  },{
    _id:123113,
    type:"type2"
    msg:""
  },{
    _id:123134,
    type:"type2"
    msg:""
  }
}

例如数据表结构如上,想要同时(一条查询语句)查询type="type1"的随机一条记录和type="type2"的随机一条记录,分开两次查询已经学会了。如果要一次查询出来应该怎么写呢?

4 回复

where({

type:db.command.in([“type1”,“type2”])

}).limit(2)

这样呢,不过应该不会随机

请在云函数中使用

// 云函数入口文件

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()

}

where({

type: _.eq(‘type1’).or(_.eq(‘type2’))

})

回到顶部