【uniCloud】数据表按照某个字段进行去重

该文章描述了如何使用uniCloud的数据库API,通过MongoDB聚合操作来查询news表中channel指定的新闻,对title字段进行去重,只保留每条新闻的第一项数据,其余重复项被删除。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对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
	};
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值