Question

Is there a way of querying array fields within documents in mongodb using more than one condition? Example document:

{
    'title': 'A document title',
    'array_element': [
        {
            'some_identifier': 'abcdefg',
            'value': 10
        },
        {
            'some_identifier': 'hijklmnop',
            'value': 5
        },
        {
            ...etc...
        }
    ]
}

I need to query a collection to find the lowest value for a specific identifier, however these values are stored with others in an array. I know I can query the collection to find the document which contains the array element with the lowest value, and which contains the array element which matches an identifier, but I can't be sure that a specific array element will match both of these conditions. Is there a way of doing this efficiently?

Was it helpful?

Solution

You can use the $elemMatch operator to accomplish this, e.g.

foo.find( { "array_element" : 
             { $elemMatch : { 'some_identifier' : 'abcdefg', 'value' : 8 } } } );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top