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

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

问题描述

我想编写一个汇总,以识别使用多个付款来源的帐户。典型的数据是。

  {
account:abc,
vendor:amazon,
}
...
{
帐户:abc,
供应商:overstock,
}
pre>

现在,我想生成一个类似这个

的帐户列表

  {
account:abc,
vendorCount:2
}

我如何在Mongo的聚合框架中写这个

解决方案

我想通过使用$ addToSet和$ unwind运算符。



Mongodb聚合计数阵列/设置大小

  db.collection.aggregate([
{
$ group:{ _id:{account:'$ account'},供应商:{$ addToSet:'$ vendor'}}
},
{
$ unwind:$ vendors
} ,
{
$ group:{_id:$ _id,vendorCount:{$ sum:1}}
}
]

希望它有助于某人


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
}

How would I write this in Mongo's aggregation framework

解决方案

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

Mongodb Aggregation count array/set size

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

Hope it helps someone

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

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