Reputation: 15
I am trying to find the average sell of each console xbox, ps4, and wii. I am working with nested documents, and I try to access type to filter "sell" using db.console.find({"market.type":"sell"}); but I end up getting "online" type values as well.
Document 1:
_id:("111111111111111111111111")
market:Array
0:Object
type:"sell"
console:"Xbox"
amount:399
1:Object
type:"online"
console:"PS4"
amount:359
2:Object
type:"sell"
console:"xbox"
amount:349
Upvotes: 0
Views: 44
Reputation: 3812
Since you need to filter the sub-documents from a documents so simply find
will not work to filter the sub-documents.
You have to use aggregation pipeline as below:
> db.st9.aggregate([
{
$unwind:"$market"
},
{
$match: {"market.type":"sell"}
},
{
$group: {_id:"$market.console", "avg": {$avg:"$market.amount"}, "count": {$sum:1}, "totalSum": {$sum: "$market.amount"} }
}
])
Output:
{ "_id" : "PS4", "avg" : 300, "count" : 1, "totalSum" : 300 }
{ "_id" : "Xbox", "avg" : 359, "count" : 3, "totalSum" : 1077 }
>
For more reference on aggregation pipeline check below official mongo db documentations:
Upvotes: 2