mongodb使用aggregate中对于某字段去重

我需要对数据库中的品牌名称进行去下重,想到mongodb应该有和mysql一样的操作

db.ware_detail_dataplatform.distinct(field, query, options)

命令如上,如我需要对某一品牌的url进行去重,命令如下

db.ware_detail_2022_09.distinct("url",{"brand_name":"AAA"})

 但是当这个集合数据量过大时,就会报错

Error: Executor error during distinct command :: caused by :: distinct too big, 16mb cap

 此时我们需要借助aggregate来实现

$math中是搜索条件,group执行的是去重的字段

db.ware_detail.aggregate( 
            [
								{"$match": {"sources":"manufacturers"}},
                {"$group": { "_id": { brand_name: "$brand_name"} } }
            ]
        );

如果集合过大时需要使用参数allowDiskUse: true,如下所示,out代表将聚合之后的结果输出在对应的集合下

db.ware_detail_dataplatform.aggregate( 
            [
								{"$match": {"sources":"manufacturers"}},
                {"$group": { "_id": { url: "$url"} }},
								{'$out':{'db':'test','coll':'manufacturers_aggregate'}}
            ]
						, {allowDiskUse: true}
        );

mongodb使用aggregate中对于某字段去重_第1张图片

使用distinct结果

可以看到两者结果是一样的,分享到次为止,祝大家中秋快乐 

你可能感兴趣的:(mongodb,数据库)