How to hide _id from Aggregation?

后端 未结 4 1138
广开言路
广开言路 2020-12-30 21:25

I\'ve this query:

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


        
4条回答
  •  一向
    一向 (楼主)
    2020-12-30 22:02

    This is not exaclty a mongoWay of doing it, but you can use this factory to generate an object that includes all but _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 }
    }
    

    Then use it like this:

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

提交回复
热议问题