Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to project specific fields from a document inside an array?

here is a typical document

{
   title : 'someTitle',
   places : [{name : 'someName', location : 'someLocation'}, {name ...}]
}

I have the following query

var qs = {title : 'someTitle', places : {$elemMatch : {name : 'someName' } } };

where I select a document which matches the title and which contains a document entry within its 'places' array that has name equal to 'someName'. However the issue is that the entries within the places array are large documents, and I only need a couple of fields from that document. I tried projecting the fields like so but it did not work.

var projection = {'places.$.name': 1, 'places.$.location' : 1};

Which is supposed to return an array with a document containing only the 'name' and 'location' property.

I got the following error

Can't canonicalize query: BadValue Cannot specify more than one positional proj. per query.  

to be clear, I would like to accomplish this without the aggregate framework

like image 986
naughty boy Avatar asked Nov 20 '15 16:11

naughty boy


People also ask

How do I project specific fields in MongoDB?

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


1 Answers

For the fields inside an array, you can project them the same as in embedded object
var projection = {'places.name': 1, 'places.location' : 1};
Check this guideline
https://docs.mongodb.com/manual/reference/operator/aggregation/project/#include-specific-fields-from-embedded-documents

like image 60
Cao Mạnh Quang Avatar answered Sep 24 '22 02:09

Cao Mạnh Quang