Is there a way to restrict fields in aggregate
queries in MongoDB?
With a find()
you can set fields you don't want to 0
restrict everything but, and with update
s you and use the $unset
command (which isn't really the same, but close), but it doesn't seem like there's a way to do it with the aggregate
command.
When I try to set to 0
, I get:
"errmsg" : "exception: The top-level _id field is the only field currently supported for exclusion"
To rephrase this, based on the example from http://docs.mongodb.org/manual/tutorial/project-fields-from-query-results/, I would like to return all fields in the documents except certain fields. Example:
db.inventory.find( { type: 'food' }, { type:0 } )
It seems with the aggregate
command that I can only tell it what to include, not what to exclude
To exclude the _id field from the output documents of the $project stage, specify the exclusion of the _id field by setting it to 0 in the projection document.
In aggregate, $limit limits the number of documents sent to the next aggregation state, and $skip skips the first N documents, so if $skip is after $limit and $skip >= $limit, you won't get any results. In short, this is expected behavior in MongoDB.
You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});
MongoDB's cursor object has a method called skip , which as per documentation and definition, controls where MongoDB begins returning results. Thus in combination with function limit, one can easily have paginated results.
You can use a $project
stage in your pipeline to specify the fields to include in your output:
{$project: {a: 1, b: 1, _id: 0}}
Update for question update:
Unfortunately, field exclusion is only supported for _id
so you can't directly exclude type
and instead have to include all the fields that you do want.
Starting Mongo 4.2
, if your projection stage only consists in discarding fields, you can use $project
's alias $unset
:
// { a: 1, b: 2, c: 3 },
// { a: 4, b: 5, c: 6 }
db.collection.aggregate({ $unset: ["_id", "b"] })
// { a: 1, c: 3 }
// { a: 4, c: 6 }
where ["_id", "b"]
is the list of fields to discard.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With