uniCloud 数据按某字段去重

924 阅读1分钟

uniCloud 的数据操作案例还是比较少的,网上几乎无法搜索到你需要的答案,对于我这种非服务端开发者还是有点茫然。所以就 数据按某字段去重 这么一个小案例做下解决记录,给有需要的人提供个思路:

如何实现以 url 对数据进行去重?

具体的实现代码如下:

// 去重
async deduplicate() {
    const $ = this.db.command.aggregate
    const dbCmd = this.db.command
    const res = await this.collection
        .aggregate()
        .group({
            _id: '$url', // 需要去重的键
            num: $.sum(1),  // 统计组的数据
            first: $.first('$_id')  // 返回组里的第一个数据
        }).end()

    // 获取数据的 id
    const ids = res.data.map((e) => e.first)

    // 除了 ids, 其余数据进行删除
    await this.collection.where({
        _id: dbCmd.nin(ids)
    }).remove()

    return ids;
}