如何计算mongoose中的数组

时间:2017-09-09 15:39:35

标签: node.js mongodb express mongoose

如何在一个mongodb集合中对stock等于'Available'的大小相同的值进行计数和求和。

期望的结果如下:

{_id :'S',count: 5 },
{_id :'M',count: 2 },
{_id :'L',count: 1 }
"price" : 123.8,
"gender" : "women",
"colour" : "blue",
"item" : [ 
    {
        "name" : "ICE DUO ANTHRACITE YELLOW SMALL (S)",
        "size" : "S",
        "stock" : "Available",
        "_id" : ObjectId("59b2829e5acd8e2d14aa84cf")
    }, 
    {
        "name" : "ICE DUO ANTHRACITE YELLOW SMALL (L)",
        "size" : "L",
        "stock" : "Available",
        "_id" : ObjectId("59b2829e5acd8e2d14aa84ce")
    }, 
    {
        "name" : "ICE DUO ANTHRACITE YELLOW SMALL (M)",
        "size" : "M",
        "stock" : "Available",
        "_id" : ObjectId("59b2829e5acd8e2d14aa84cd")
    }
],

1 个答案:

答案 0 :(得分:1)

尝试以下:

db.users.aggregate([
{$match:{stock:'Available'}},
{$unwind: 'item'},
{$group:{_id: '$size', count:{$sum:1}}}
])