$ project不返回指定的字段

时间:2016-06-02 06:17:01

标签: python mongodb mongodb-query aggregation-framework

我的文档结构

enter image description here

这是我正在运行的......

query = self._database.suiteruns.aggregate([
    {
        "$project": {
            "name": 1,
            "user": 1,
            "endTime":1,
            "duration": 1,
            "testCases": 1,
            "verdict": 1
        }
    },
    {
        "$match": {
            "user": user_id
        }
    },
    {
        "$group": {
            "_id": "$name",
            "count": {
                "$sum": "$name"
            }
        }
    },
    {
        "$sort": {
             "updatedTime": -1
        }
    }
])

运行上述查询后的结果

[
  {
   u'count': 0, 
   u'_id': u"Minor GC003"
  }
  .
  .
  .
  . some more objects like this(without the fields mentioned in $project)
]

*预期结果*

[
{
 "verdict": "",
 "testCases" : [{}],
 .
 .
 . (other fields)
}]

我想在名称字段上进行分组并按用户进行匹配,并期望我在$项目中提到的其他字段,但我仍然没有得到其他字段。 任何帮助/讨论都会很棒......

1 个答案:

答案 0 :(得分:0)

您可以尝试以下方式: -

self._database.suiteruns.aggregate(
   [
      {$match : {"user": user_id}},
      { $group : {
           "_id" : "$name", 
           "result": { $push: "$$ROOT" },     
           "count": 
           {
                "$sum": "$name"
           } 
        }
     }
   ]
)

结果将是

[
  {
    'count': 0, 
    '_id': u"Minor GC003",
    'result':[{
                'name': 'abcd',
                //All the fields of root level
             }]
  }
]

希望这会有所帮助。有关详细信息,请参阅$group