MongoDB聚合:计算不同的字段 [英] MongoDB Aggregation: Counting distinct fields

查看:15
本文介绍了MongoDB聚合:计算不同的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个聚合来识别使用多个付款来源的帐户.典型的数据是.

I am trying to write an aggregation to identify accounts that use multiple payment sources. Typical data would be.

{
 account:"abc",
 vendor:"amazon",
}
 ...
{
 account:"abc",
 vendor:"overstock",
}

现在,我想生成一个与此类似的帐户列表

Now, I'd like to produce a list of accounts similar to this

{
 account:"abc",
 vendorCount:2
}

我将如何在 Mongo 的聚合框架中编写此代码

How would I write this in Mongo's aggregation framework

推荐答案

我通过使用 $addToSet 和 $unwind 运算符解决了这个问题.

I figured this out by using the $addToSet and $unwind operators.

Mongodb 聚合计数数组/集合大小

db.collection.aggregate([
{
    $group: { _id: { account: '$account' }, vendors: { $addToSet: '$vendor'} }
},
{
    $unwind:"$vendors"
},
{
    $group: { _id: "$_id", vendorCount: { $sum:1} }
}
]);

希望对某人有所帮助

这篇关于MongoDB聚合:计算不同的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆