Pokkke
Pokkke

Reputation: 65

MongoDB, find field into array

I have items like these in my collection

{
user: data,
somestuff: [somedata ...], 
terminals: [ {
   label: data,
   details: [{more content}, {}, ...]
   }]
}

I would use 'find' to extract "details" field for a specific terminal 'label' I know that there is an easy way to get the "terminals" array by:

collection.find({_id: "..."}, {_id:0, terminals: 1})

Wich return

{ terminals: [ {
   label: data,
   details: [{more content}, {}, ...]
   }]
}

I tried

collection.find({ "terminals.label": data }, { _id: 0, "terminals.$.details": 1 })

As edirican has suggested And it almost work, but it return the same structure than previously except that the terminals list contain only the labeled document

The result I expect is the details list, extracted from terminals

{ details: [{more content}, {}, ...] }

Thanks for your help !

Upvotes: 1

Views: 138

Answers (1)

Ebubekir Dirican
Ebubekir Dirican

Reputation: 386

Use positional ($) projection.

http://docs.mongodb.org/manual/reference/operator/projection/positional/

collection.find({ "terminals.label": 2 }, { _id: 0, "terminals.$.details": 1 })

Upvotes: 1

Related Questions