MongoDB聚合 - 是否可以获得匹配的值而不是sum,count,avg等

时间:2015-12-02 13:38:56

标签: mongodb mongodb-query aggregation-framework

见下文,

 [
     {

        "memberId": "m1",
        "positionId": "pos1",
        "projectId": "prj1"
    },

    {

        "memberId": "m1",
        "positionId": "pos2",
        "projectId": "prj1"
    },

    {

        "memberId": "m1",
        "positionId": "pos3",
        "projectId": "prj2"
    },

    {

        "memberId": "m1",
        "positionId": "pos5",
        "projectId": "prj2"
    },

    {

        "memberId": "m2",
        "positionId": "pos3",
        "projectId": "prj2"
    }
]

我需要为给定的 memberId 生成输出, 按 projectIds 分组,并返回 projectId的 positionId

说,

{
"result" : [ 
    {
        "_id" : {
            "project" : "prj2",
            "position" : ["pos5", "pos3"]
        }
    }, 
    {
        "_id" : {
            "project" : "prj1",
            "position" : ["pos2","pos1"]
        }
    } 

]}

3 个答案:

答案 0 :(得分:1)

您无法使用$push运算符创建复合_id字段。最好的办法是$group by" projectId'并返回"位置"作为数组。

db.collection.aggregate([
    { '$group': {
        '_id': '$projectId', 
        'position': { '$push': '$positionId' }
    }}
])

返回:

{ "_id" : "prj2", "position" : [ "pos3", "pos5", "pos3" ] }
{ "_id" : "prj1", "position" : [ "pos1", "pos2" ] }

但如果你真的觉得需要一个复合_id字段,那么还需要一个$group阶段。

db.collection.aggregate([
    { '$group': {
        '_id': '$projectId', 
        'position': { '$push': '$positionId' }
    }},
    { '$group': {
        '_id': { 
            'project': '$_id', 
            'position': '$position'
        }
    }}
])

哪个收益率:

{ "_id" : { "project" : "prj1", "position" : [ "pos1", "pos2" ] } }
{ "_id" : { "project" : "prj2", "position" : [ "pos3", "pos5", "pos3" ] } }

答案 1 :(得分:0)

这种聚合可能有所帮助,其结果与您提到的输出相同。

db.test.aggregate(
   [
      {
        $group : {
           _id : {"project" : "$projectId"},
           position: { $addToSet:"$positionId"  }
        }
      }
   ]
)

答案 2 :(得分:0)

db.collection.aggregate([
  {$match:{"memberId" : "m1"}},
  {$group:{_id:"$projectId", positions:{$addToSet:"$positionId"}}},
 {$project:{_id:0, "project":"$_id", positions:1}}
])

输出

{
"result" : [ 
    {
        "positions" : [ 
            "pos5", 
            "pos3"
        ],
        "project" : "prj2"
    }, 
    {
        "positions" : [ 
            "pos2", 
            "pos1"
        ],
        "project" : "prj1"
    }
],
"ok" : 1

}