How to retrieve limit no of fields from mongodb easily if I have 100s of fields in the collection?

I have a document below,

key1: ‘value1’,
key2: ‘value2’,
key3: ‘value3’,
key4: ‘value4’,
key5: ‘value5’,
key6: ‘value6’,
key7: ‘value7’,
key8: ‘value8’,
key9: ‘value9’,
key10: ‘value10’,
key11: ‘value11’,
key12: ‘value12’,
key13: ‘value13’,
key14: ‘value14’,

I want to retrieve only ‘value14’, for that I can write a query like
db.samplecol.find({},{key1: 0, key2: 0, key3: 0, key4: 0, key5: 0, key6: 0, key7: 0, key8: 0, key9: 0, key10:0, key11: 0, key12: 0, key13: 0, key14:1});

To retrieve only key14 , i have to make every other keys make as 0.
Without that is there any way to do like
db.sample.find({}, {key14: only})?

Are you using the field specifiers correctly?

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.

1 Like

It should be sampleCollection.find({}, { fields: { key14: 1 } })


I think the issue is that he is mixing inclusion and exclusion together - one one is possible in one query.

1 Like