如何在Model.distinct()之后获取与不同值相关的所有字段

我有这样的架构:

var PricelistSchema = new Schema({ Category : String, Family: String, Others: String, Brand: String, Volume: Number, Price: Number, City: String }); 

我用Model.distinct()方法获得了“ Family fieldDistinct values 。 但问题是我也需要知道每个不同的家庭价值类别的相应价值。

我试图通过MapReduce做,但我似乎无法得到正确的结果。 有人可以帮助我,这真的很重要。

样本输出:

 { "_id": "56af4c63ad0fd9ec149694d2", "Category": "Rum", "Others": "0", "Family": "Old Monk", "Brand": "OLD MONK WHITE RUM", "Volume": 375, "Price": 220, "City": "Delhi" }, { "_id": "56af4c63ad0fd9ec149694d3", "Category": "Rum", "Others": "0", "Family": "Old Monk", "Brand": "OLD MONK WHITE RUM", "Volume": 750, "Price": 440, "City": "Delhi" } 

我有近3000个这样的文件。 我只需要在数据库中获得不同的姓氏,但每个姓氏都应该有与之相关的类别。

现在我得到:

 ["old Monk", "Crimson", "Cutty Sark", "Dennis", "Director's Special", "Discovery", "Double Blue", "Evening Special", "Everyday Gold", "Frontline", "Glider Superior", "Golden Border", "Golfer's Shot", "Good Day", "Haig Gold", "Havaldar", "Hero No.1", "Impact", "Imperial Blue", "King Henry", "King's Gold", "Malbros Rich" ] 

在数组中,我也需要每个字段的类别。 谢谢

对于这种情况, 聚合框架将是理想的,因为您需要使用$group操作符按Family字段对文档进行分组,并使用$addToSet累加器操作符创build一个数组,以便为​​每个分组文档保存不同的Category值。

聚合pipe道将具有以下操作步骤作为aggregate()方法参数:

 // Define the pipeline var pipeline = [ { "$group": { "_id": "$Family", "Categories": { "$addToSet": "$Category" } } } ]; // Run the pipeline PriceList.aggregate(pipeline) .exec(function (err, result){ if (err) { /* Handle error */}; console.log(JSON.stringify(result, null, 4)); }); 

或者使用stream畅的API来运行pipe道:

 PriceList.aggregate() .group({ "_id": "$Family", "Categories": { "$addToSet": "$Category" } }) .exec(function (err, result){ if (err) { /* Handle error */}; console.log(JSON.stringify(result, null, 4)); });