Projections
- It is a feature using which we can decide which field to show in the result.
- To include a certain fields use projection value of 1.
shop> db.comments.find({'comments': {$size: 4}}, {comments: 1})
[
{
_id: 1,
comments: [
{ user: 'Alice', text: 'Great article!' },
{ user: 'Bob', text: 'Thanks for sharing.' },
{ user: 'Eva', text: 'Its beatifull!' },
{ user: 'jessy' }
]
}
]
- To exclude a certain fields use projection value of 0.
shop> db.comments.find({'comments': {$size: 4}}, {comments: 1, _id: 0})
[
{
comments: [
{ user: 'Alice', text: 'Great article!' },
{ user: 'Bob', text: 'Thanks for sharing.' },
{ user: 'Eva', text: 'Its beatifull!' },
{ user: 'jessy' }
]
}
]
- You can't include and exclude the fields at a same time. [Exception: _id can be exluded with comments included in the last example]
shop> db.comments.find({'comments': {$size: 4}}, {comments: 1, author:0, _id: 0})
MongoServerError: Cannot do exclusion on field author in inclusion projection
shop> db.comments.find({'comments': {$size: 4}}, {comments: 1, author:0})
MongoServerError: Cannot do exclusion on field author in inclusion projection