Field specifiers

Field Specifiers

Queries can specify a particular set of fields to include or exclude from the result object.

To exclude specific fields from the result objects, the field specifier is a dictionary whose keys are field names and whose values are 0. All unspecified fields are included.

Users.find({}, {fields: {password: 0, hash: 0}})

To include only specific fields in the result documents, use 1 as the value. The _id field is still included in the result.

Users.find({}, {fields: {firstname: 1, lastname: 1}})

With one exception, it is not possible to mix inclusion and exclusion styles: the keys must either be all 1 or all 0. The exception is that you may specify _id: 0 in an inclusion specifier, which will leave _id out of the result object as well. However, such field specifiers can not be used with observeChanges, observe, cursors returned from a publish function, or cursors used in {{#each}} in a template. They may be used with fetch, findOne, forEach, and map.

Field operators such as $ and $elemMatch are not available on the client side yet.

A more advanced example:

Users.insert({ alterEgos: [{ name: "Kira", alliance: "murderer" },
                           { name: "L", alliance: "police" }],
               name: "Yagami Light" });

Users.findOne({}, { fields: { 'alterEgos.name': 1, _id: 0 } });

// returns { alterEgos: [{ name: "Kira" }, { name: "L" }] }

See the MongoDB docs for details of the nested field rules and array behavior.

doc_Meteor
2016-05-29 17:20:32
Comments
Leave a Comment

Please login to continue.