Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to restrict fields in an aggregate query?

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 updates 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

like image 579
FuriousGeorge Avatar asked Apr 19 '15 19:04

FuriousGeorge


People also ask

How do I exclude fields in MongoDB?

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.

How do you use aggregate limits?

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.

How do I display only one column in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});

What is skip in MongoDB?

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.


2 Answers

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.

like image 164
JohnnyHK Avatar answered Sep 22 '22 01:09

JohnnyHK


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.

like image 44
Xavier Guihot Avatar answered Sep 23 '22 01:09

Xavier Guihot