MongoDB query to retrieve one array value by a value in the array -


i have collection of documents each contain array of sub documents. each subdocument has time value. trying see if can return sub document, based on time in sub document.

i know can retrieve sub document using $slice, $slice give me specific index or range , offset.

example time!

documents so....

{      id: 1234,      type: 'a',      subs: [         { time: 123001, val: 'a' },         { time: 123002, val: 'b' },         { time: 123003, val: 'c' }     ] } 

if query find({}, {subs: {$slice: [2,1]}}) like:

{ id: 1234, type: 'a', subs: [{ time: 123002, val: 'b' }]} 

i want retrieve record example based not on offset, based on 123002 time value.

possible?

go!

as you've designed data not possible.

in mongodb, queries return entire document. can filter specific fields, if value of field array, stops there.

when have "arrays of objects", either have $slice, not want, or have model data differently.

in case, following structure make query possible:

{      _id: 1234,      type: 'a',      subs: {         '123001': { val: 'a' },         '123002': { val: 'b' },         '123003': { val: 'c' }     } } 

notice how i've changed subs json object instead of array. can following query , time you're looking for:

find( { _id: 1234 }, { 'subs.123002': 1 } ) 

the obvious trade-off here have change way use change document. cannot use $push on subs, cannot query {'subs.time': 1234}, instead have query {'subs.1234': { $exists:true} }.


Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -