gpt4 book ai didi

MongoDB 聚合 : Counting distinct fields

转载 作者:IT老高 更新时间:2023-10-28 13:04:09 27 4
gpt4 key购买 nike

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

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

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

{
account:"abc",
vendorCount:2
}

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

最佳答案

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

Mongodb Aggregation count array/set size

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

希望对某人有所帮助

关于MongoDB 聚合 : Counting distinct fields,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18501064/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com