mongoDB 去重统计, group实现版

mongoDB 统计去重后的count,用$group实现

	db.collection.aggregate([
		{$group: {_id: '$myData'}},
	    {$count: 'myCount'}
	], {
	    maxTimeMS: 60000, // aggregate 超时时间,数据量大时需设置大些
	    allowDiskUse: true, // 数据量大时需启用
	})

NodeJS 版完整代码:

/*
在myDb.myCollection中存有以下数据:
[
	{_id: 1, myData: 'a'},
	{_id: 2, myData: 'b'},
	{_id: 3, myData: 'c'},
	{_id: 4, myData: 'b'},
	{_id: 5, myData: 'a'},
]
统计 myData 去重后的数据数量
getDistinctCount() // return 3;          myData ['a', 'b', 'c']
*/
const MongoClient = require('mongodb').MongoClient;

const getCollection = async () => {
	const url = 'mongodb://localhost:27017';
	const DB_NAME = 'myDb';
	const COLLECTION_NAME = 'myCollection';
	
	const client = await MongoClient.connect(url);
	const db = client.db(DB_NAME);
	const collection = db.collection(COLLECTION_NAME);
	return collection;
}


const getDistinctCount = async () => {
	const collection = await getCollection();
	const [res = {}] = await collection.aggregate([
		{$group: {_id: '$myData'}},
	    {$count: 'myCount'}
	], {
	    maxTimeMS: 60000, // aggregate 超时时间,数据量大时需设置大些
	    allowDiskUse: true, // 数据量大时需启用, requires mongodb 2.6 >
	}).toArray();
	return res.myCount;
}

你可能感兴趣的:(nodeJS,Database)