Reputation: 937
I'm very new beginner in mongoDB.
we have to show output data in which having
Unique number of user by date.
Number of Android user and Ios user.
This is input JSON data
Input
[{
'name' : 'user1',
'date' : '23/09/2017',
'deviceType' : 'Android'
},
{
'name' : 'user2',
'date' : '24/09/2017',
'deviceType' :'ios'
},
{
'name' : 'user1',
'date' : '23/09/2017',
'deviceType' :'ios'
},
{
'name' : 'user2',
'date' : '23/09/2017',
'deviceType' :'ios'
},
{
'name' : 'user1',
'date' : '24/09/2017',
'deviceType' :'ios'
},
{
'name' : 'user2',
'date' : '25/09/2017',
'deviceType' :'Android'
}
]
I'm very confused what is query to fetch required data.
And Output is
Output
[{
'date' : '23/09/2017',
'iosCount': 2,
'androidCount':1
},
{
'date' : '24/09/2017',
'iosCount': 2,
'androidCount':0
},
{
'date' : '25/09/2017',
'iosCount': 0,
'androidCount':1
}
]
Upvotes: 1
Views: 65
Reputation: 106
@ Buzz Moschetti
If date "23/09/2017" has input data like
[{'name' : 'user1','date' : '23/09/2017','deviceType' : 'Android'},
{'name' : 'user1','date' : '23/09/2017','deviceType' :'ios'},
{'name' : 'user1','date' : '23/09/2017','deviceType' : 'Android'},
{'name' : 'user2','date': '23/09/2017','deviceType':'ios'}]
output
[{'date' : 23/09/2017, totalIos : 2, totalAndroid: 1}]
user1 has data 2 android and 1 Ios data. So only 1 android data will be count.
Upvotes: 1
Reputation: 7621
Here's one solution, and it is neutral to device types. If you add more, the agg pipeline will adapt to the new values.
db.foo.aggregate([
{$group: {_id: {d:"$date",t:"$deviceType"}, n: {$sum:1}}}
,{$group: {_id: "$_id.d", devices: {$push: {type:"$_id.t", n:"$n"}} }}
]);
{
"_id" : "24/09/2017",
"devices" : [
{
"type" : "ios",
"n" : 2
}
]
{
"_id" : "23/09/2017",
"devices" : [
{
"type" : "ios",
"n" : 2
},
{
"type" : "Android",
"n" : 1
}
]
}
{
"_id" : "25/09/2017",
"devices" : [
{
"type" : "Android",
"n" : 1
}
]
}
If you really want exactly the output you seek:
db.foo.aggregate([
{$group: {_id: "$date",
iosCount: {$sum: {$cond: [ {$eq: [ "$deviceType","ios"]}, 1, 0 ] }},
androidCount: {$sum: {$cond: [ {$eq: ["$deviceType","Android"]}, 1, 0] }}
}}
]);
Upvotes: 1