如何从聚合隐藏_id?(How to hide _id from Aggregation?)

2019-08-19 04:09发布

我有此查询:

produits = yield motor.Op(db.users.aggregate, [{"$unwind":"$pup"},{"$match":{"pup.spec.np":nomp}}, {"$group":{"_id":"$pup.spec.id","pup":{"$push":"$pup"}}}])

这给了我这样的结果:

print produits

{u'ok': 1.0, u'result': [{u'_id': None, u'pup': [{u'avt': {u'fto': ..all the results}}]}]}

所以我可以做:

prod = produits["result"]

[{u'_id': None, u'pup': [{u'avt': {u'fto': ..all the results}}]}]

但我怎么能隐藏"_id"所以,我只能得到:

[{u'pup': [{u'avt': {u'fto': ..all the results}}]}]

在一个正常的查询,我只想补充一点像{"_id":0}但在这里是行不通的。

Answer 1:

从MongoDB的文档

您可以$投影结果排除_id -这是什么意思?

http://docs.mongodb.org/manual/reference/aggregation/#pipeline

注意_id字段默认总是包括在内。 你可以明确排除_id如下:

db.article.aggregate(
    { $project : {
        _id : 0 ,
        title : 1 ,
        author : 1
    }}
);

从你例如,在管道中的第一个操作将排除_id,并包括其他attribs。



Answer 2:

我不熟悉的运动,但你应该能够从结果快译通直接删除属性。

>>> produits = {u'ok': 1.0, u'result': [{u'_id': None, u'pup': [{u'avt': {u'fto': 'whatever'}}]}]}
>>> prod = produits['result'] 
>>> del prod[0]['_id']
>>> print prod
[{u'pup': [{u'avt': {u'fto': 'whatever'}}]}]


Answer 3:

开始Mongo 4.2 ,在$unset聚集运算符可以用来作为一种替代语法$project仅用于降字段时:

// { _id: "1sd", pup: [{ avt: { fto: "whatever"} }] }
// { _id: "d3r", pup: [{ avt: { fto: "whatever else"} }] }
db.collection.aggregate({ $unset: ["_id"] })
// { pup: [{ avt: { fto: "whatever" } } ] }
// { pup: [{ avt: { fto: "whatever else" } } ] }


Answer 4:

这不是exaclty做这件事的mongoWay,但您可以使用此工厂生成的对象包括所有,但_id

/**
 * Factory that returns a $project object that excludes the _id property https://docs.mongodb.com/v3.0/reference/operator/aggregation/project/ 
 * @params {String} variable list of properties to be included  
 * @return {Object} $project object including all the properties but _id
 */
function includeFactory(/* properties */){
    var included = { "_id": 0 };
    Array.prototype.slice.call(arguments).forEach(function(include){
        included[include] = true
    })

    return { "$project": included }
}

然后使用它是这样的:

cities.aggregate(
{ "$group": { "_id": null, "max": { "$max": "$age" }, "min": { "$min": "$age" }, "average": { "$avg": "$age" }, "total": { "$sum": "$count" } } },
        includeFactory('max','min','average','total') 
)


文章来源: How to hide _id from Aggregation?