云数据库聚合查询时,利用$.setUnion或$.setDifference对数组型字段去重
发布于 4 年前 作者 yeqiang 4168 次浏览 来自 分享

查遍文档也没找到去重的办法,最后发现这两个函数可以曲线救国

https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-sdk-api/database/command/aggregate/AggregateCommand.setUnion.html

https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-sdk-api/database/command/aggregate/AggregateCommand.setDifference.html

假设某一条记录中存在一个数组型元素suppliers

suppliers: ['a', 'a', 'b', 'c']

首先试试setUnion,函数的作用是输出两个数组的并集,那么加入一个空数组,相当于去重示例如下:

await db.collection('orders')
    .aggregate()
    .addFields({
      suppliersDistinct: $.setUnion(['$suppliers', []])
    }).end()

输出结果为:

suppliers: ['a', 'b', 'c']

再用setDifference,函数作用是输出仅存在第一个数组中值,可以用于先排除一个指定值,这里想排除c,示例如下

await db.collection('orders')
    .aggregate()
    .addFields({
      suppliersDistinct: $.setDifference(['$suppliers', ['c']])
    }).end()

输出结果为:

suppliers: ['a', 'b']
回到顶部