mongodb从数组中选择项目,将它们分组并计算总数

时间:2015-09-28 14:04:51

标签: mongodb aggregation-framework

当我这样写的时候

db.Profiles.find({ userId:4790, "p2l.listId":31618 }, { "p2l.$": 1 } )

我得到了理想的结果

 ...
 {
    "_id" : ObjectId("56052d35df3e5e564f770ed0"),
    "p2l" : [ 
        {
            "listId" : 31618,
            "status" : 131
        }
    ] }

{
    "_id" : ObjectId("56052d25df3e5e564f770ecd"),
    "p2l" : [ 
        {
            "listId" : 31618,
            "status" : 25
        }
    ] }

 {
    "_id" : ObjectId("56052d1adf3e5e564f770eca"),
    "p2l" : [ 
        {
            "listId" : 31618,
            "status" : 25
        }
    ] }

 {
    "_id" : ObjectId("5603c882bd1f3d3668ba7352"),
    "p2l" : [ 
        {
            "listId" : 31618,
            "status" : 24
        }
    ] }

,但我必须按状态分组

我怎么做?

我试着

 db.Profiles.aggregate( {$match:{  userId:4790, "p2l.listId":31618}},

{$project:{"p2l.listId":"$p2l.listId", "p2l.status":"$p2l.status"}} )

但是在rezult中,我有值,不符合请求的参数。结果,listId = 31617

{
    "result" : [ 
        ...
        {
            "_id" : ObjectId("56052d25df3e5e564f770ecd"),
            "p2l" : [ 
                {
                    "listId" : [ 
                        31618
                    ],
                    "status" : [ 
                        25
                    ]
                }
            ]
        }, 
        {
            "_id" : ObjectId("56052d1adf3e5e564f770eca"),
            "p2l" : [ 
                {
                    "listId" : [ 
                        31618, 
                        31617
                    ],
                    "status" : [ 
                        25, 
                        25
                    ]
                }, 
                {
                    "listId" : [ 
                        31618, 
                        31617
                    ],
                    "status" : [ 
                        25, 
                        25
                    ]
                }
            ]
        }, 
        {
            "_id" : ObjectId("5603c882bd1f3d3668ba7352"),
            "p2l" : [ 
                {
                    "listId" : [ 
                        31618
                    ],
                    "status" : [ 
                        24
                    ]
                }
            ]
        }
    ],
    "ok" : 1.0000000000000000,
    "$gleStats" : {
        "lastOpTime" : Timestamp(0, 0),
        "electionId" : ObjectId("5606384b5e0803423d340427")
    }
}

1 个答案:

答案 0 :(得分:0)

我找到了一个解决方案,这是一个例子

 db.Profiles.aggregate(
  { $match : {
     "p2l.listId": 31618
  }},
  { $unwind : "$p2l" },
  { $match : {
     "p2l.listId": 31618
  }},
  {$project:{"p2l":"$p2l"}},
  {$group:{_id : { "p2l.status": "$p2l.status"},
  "count": { $sum: 1 }}}
)