MongoDB query creates OR instead of OR

I am using MongoDB version 2.6.5, and I have a collection that looks something like this:

{ "_id": ObjectId("555a3398f4c572a44f877dcd"), "created": ISODate("2015-05-18T17:02:14.951Z"), "values": [ { "value": "4", "label": "Apple" }, { "value": "5", "label": "Peach" }, { "value": "5", "label": "Banana" }, { "value": "4", "label": "Orange" } ], "__v": 0 } { "_id": ObjectId("555a74dbdfe135105faccdf7"), "created": ISODate("2015-05-18T21:27:37.064Z"), "values": [ { "value": "2", "label": "Apple" }, { "value": "3", "label": "Peach" }, { "value": "4", "label": "Banana" }, { "value": "5", "label": "Orange" } ], "__v": 0 } { "_id": ObjectId("555a74f9dfe135105faccdfa"), "created": ISODate("2015-05-18T21:27:37.064Z"), "values": [ { "value": "1", "label": "Apple" }, { "value": "1", "label": "Peach" }, { "value": "1", "label": "Banana" }, { "value": "1", "label": "Orange" } ], "__v": 0 } 

When I try to get the document with values.label "Orange" and values.value from "5", I have to return one document, but I get two:

 > db.answers.count({ 'values.label':'Orange', 'values.value':'5' }) > 2 

This selects two documents with identifiers: 555a3398f4c572a44f877dcd (presumably because Banana also has a value of 5) and 555a74dbdfe135105faccdf7 (which is the only correct one). Can anyone think why this is happening?

+6
source share
1 answer

You use dot notation (used to access objects) in an array. Although this works as you described, it implies OR logic because the entire array is interpreted as an object, so to speak.

You are looking for a match of several criteria in the documents in the array, which is what the $elemMatch operator means, i.e.

 db.answers.count({ 'values' : { '$elemMatch' : { 'label':'Orange', 'value':'5' } } }) 
+7
source

Source: https://habr.com/ru/post/988471/


All Articles