【问题标题】:$project does not return the specified fields$project 不返回指定的字段
【发布时间】:2016-06-02 06:17:01
【问题描述】:

我的文档结构

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

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)
}]

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

【问题讨论】:

  • 文档结构在我的端没有显示,你能确定它是否在你的端添加并显示。图像未显示在我身边
  • 你是说图片?
  • 或者查询没有任何结果?
  • 我认为你不应该同时使用$project$group。首先你在做项目,然后$group 覆盖来自$project 的结果。尝试从您的查询中删除 $group,这样会正常工作。
  • 由于这是一个 IO 问题,如果您能向我们展示给定示例文档的预期文档输出,那将非常有帮助。

标签: python mongodb mongodb-query aggregation-framework


【解决方案1】:

您可以尝试以下方式:-

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

【讨论】:

  • 看起来不错,让我检查一下,然后返回 GOD SPEED。
  • $push 不适用于 root,而是我手动添加了所有字段
  • 字段路径名中不允许使用 $
  • 你的mongodb版本是多少?是否低于“2.6”?
  • 我在终端中看到的是 2.6.11
猜你喜欢
  • 2014-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
相关资源
最近更新 更多