简体   繁体   English

Pymongo 聚合() $project

[英]Pymongo aggregate() $project

I want to exclude the '_id' field and replace it with 'action_id' field when using aggregate.我想在使用聚合时排除“_id”字段并将其替换为“action_id”字段。 The problem that i must specify all other fields in $project that i dont want to exclude.我必须在 $project 中指定我不想排除的所有其他字段的问题。 This is my query:这是我的查询:

cursor = db.aggregate(
        {
            '$group': {
                '_id': '$somefield',
                'count': {'$sum': 1},
                'average_latency': {'$avg': '$latency'}
            }
        },
        {
            '$project': {
                'action_id': '$_id',
                '_id': False,
                'count': True,
                'average_latency': True
                }
        }

What shall i do to avoid writing every 'field': True in $project?我该怎么做才能避免在 $project 中写入每个“字段”:True?

You can use $addFields to add an extra field and then $project to remove _id您可以使用$addFields添加一个额外的字段,然后使用$project删除_id

cursor = db.aggregate(
  { '$group': {
    '_id': '$somefield',
    'count': { '$sum': 1 },
    'average_latency': { '$avg': '$latency' }
  }},
  { '$addFields': { 'action_id': '$_id' }},
  { '$projects': { '_id': False }}
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM