Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide _id from Aggregation?

I've this query:

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

which gives me this result:

print produits

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

so I can do:

prod = produits["result"]

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

but how can I hide "_id" so that I can only get:

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

in a normal query I would simply add something like {"_id":0} but here it doesn't work.

like image 371
Abdelouahab Pp Avatar asked Apr 02 '13 23:04

Abdelouahab Pp


3 Answers

From mongodb docs

You can $project the results to exclude the _id - is this what you mean?

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

Note The _id field is always included by default. You may explicitly exclude _id as follows:

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

From you're example, the first operation in the pipeline would be to exclude the _id and include the other attribs.

like image 58
sambomartin Avatar answered Nov 13 '22 11:11

sambomartin


Starting Mongo 4.2, the $unset aggregation operator can be used as an alternative syntax for $project when used to only drop fields:

// { _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" } } ] }
like image 36
Xavier Guihot Avatar answered Nov 13 '22 09:11

Xavier Guihot


I'm not familiar with motor, but you ought to be able to delete the property from the results dict directly.

>>> 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'}}]}]
like image 2
Michael Pratt Avatar answered Nov 13 '22 10:11

Michael Pratt