【发布时间】:2020-03-19 04:56:34
【问题描述】:
我有以下文件
users = [
{
type: 'A',
name: 'anil',
logins: [
{ at: '2-3-2019', device: 'mobile' },
{ at: '3-3-2019', device: 'desktop' },
{ at: '4-3-2019', device: 'tab' },
{ at: '5-3-2019', device: 'mobile' }
]
},
{
type: 'A',
name: 'rakesh',
logins: [
{ at: '2-3-2019', device: 'desktop' },
{ at: '3-3-2019', device: 'mobile' },
{ at: '4-3-2019', device: 'desktop' },
{ at: '5-3-2019', device: 'tab' }
]
},
{
type: 'A',
name: 'rahul',
logins: [
{ at: '2-3-2019' device: 'tab' },
{ at: '3-3-2019' device: 'mobile' },
{ at: '4-3-2019' device: 'tab' },
{ at: '5-3-2019' device: 'tab' }
]
}
]
我需要计算每个用户使用“A”类型设备的百分比。
如果我们查看用户 anil 设备使用情况,
mobile: 50%
desktop: 25%
tab: 25%
使用率最高的是移动设备,使用率50%,因此应将其视为移动设备。 就像上面的最终输出一样,
[
{
name: 'anil',
device: 'mobile',
logins: 50%
},
{
name: 'rakesh',
device: 'desktop',
logins: 50%
},
{
name: 'rahul',
device: 'tab',
logins: 75%
}
]
感谢您的帮助。
【问题讨论】:
-
这可以使用 javascript
.reduce方法来实现,但是由于您希望 mongo 进行处理,请查看 mongo docs 中的https://docs.mongodb.com/manual/aggregation/#map-reduce方法
标签: node.js mongodb mongodb-query aggregation-framework