对news新闻表按条件channel进行查询,title标题字段进行去重操作;重复数据只保留一项
'use strict';
const db = uniCloud.database()
const news = db.collection('news')
exports.main = async (event, context) => {
console.log('event.channel:', event.channel);
const channel = event.channel;
//event为客户端上传的参数
async function deduplicate(channel) {
const $ = db.command.aggregate
const dbCmd = db.command
const res = await news
.aggregate()
.match({
channel: channel
})
.group({
_id: '$title', // 需要去重的键
num: $.sum(1), // 统计组的数据
first: $.first('$_id') // 返回组里的第一个数据
})
.end()
console.log(res.length)
// 获取数据的 id
const ids = res.data.map((e) => e.first)
console.log(ids.length)
// 除了 ids, 其余数据进行删除
await news.where({
_id: dbCmd.nin(ids),
channel
}).remove()
return ids.length;
}
const remainingCount = await deduplicate(channel)
return {
code: 0,
remainingCount
};
};