How to exclude _id without including other fields using the aggregation framework

怎甘沉沦 提交于 2021-02-08 03:37:30

问题


I would like to get the result of an aggregation pipeline without the _id filed. I know this is possible if you provide explicitly other fields that will be the output of the projection. But, ¿how can I mimic the $projec in a find call?

This is what I want (No field explicitly included):

db.col.find({},{_id:0})

But in the aggregation framework seems to be impossible:

db.col.aggregate([{'$project': {_id:0}}])

Error: Printing Stack Trace
    at printStackTrace (src/mongo/shell/utils.js:37:15)
    at DBCollection.aggregate (src/mongo/shell/collection.js:927:9)
    at (shell):1:11
2013-10-07T16:36:09.273+0200 aggregate failed: {
    "errmsg" : "exception: $projection requires at least one output field",
    "code" : 16403,
    "ok" : 0
} at src/mongo/shell/collection.js:928

Any idea to workaround this issue ?


回答1:


When using aggregation, you must explicitly include/exclude fields. So, you'd need to list all the fields you want. It's not equivalent to find. So, you might:

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

Using the aggregation framework also comes with some limits you should be aware of. It's designed for aggregation (grouping, summing, etc.), so having many fields in a projection isn't as typical (and could cause results to exceed the maximum allowed, which is 16MB).



来源:https://stackoverflow.com/questions/19227807/how-to-exclude-id-without-including-other-fields-using-the-aggregation-framewor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!