monogoDBは統計を取りに行きます.groupは版を実現します.

6860 ワード

monogoDB統計で重さの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;
}