Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$or statement in $elemMatch

Tags:

Is there a way to do an $or statement in element match?

I have this:

opened: {     $elemMatch: {         closed: false         openingEvening: {$lte: currentTime},          closingEvening: {$gte: currentTime},     } } 

and would like to add openingMorning to the l

How can I extend it as:

opened: {     $elemMatch: {         closed: false         {$or: [             {openingEvening: {$lte: currentTime}, closingEvening: {$gte: currentTime},},             {openingMorning: {$lte: currentTime}, closingMorning: {$gte: currentTime}}          ]         }     } } 

is something like this possible?

like image 996
user1213904 Avatar asked May 18 '14 21:05

user1213904


People also ask

When to use elemMatch in MongoDB?

The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria. If you specify only a single <query> condition in the $elemMatch expression, and are not using the $not or $ne operators inside of $elemMatch , $elemMatch can be omitted.

Which of the following projection operators are not supported by FIND () operations on views I II $elemMatch III $slice IV $meta?

find() operations on views do not support $elemMatch projection operator.


1 Answers

Sure it is, just clearing up the syntax but you basically had it:

{     "opened": {         "$elemMatch": {             "closed": false,             "$or": [                 {                     "openingEvening": { "$lte": currentTime  },                     "closingEvening": { "$gte": currentTime  }                 },                 {                     "openingMorning": { "$lte": currentTime },                     "closingMorning": { "$gte": currentTime  }                 }              ]         }     } } 

And given a sample idea of the data:

{     "_id" : ObjectId("537969cee90c3db84958aa86"),     "opened" : [             {                     "closed" : false,                     "openingEvening" : 17,                     "closingEvening" : 22,                     "openingMorning" : 11,                     "closingMorning" : 14             }     ] } {     "_id" : ObjectId("53796a47e90c3db84958aa87"),     "opened" : [             {                     "closed" : false,                     "openingMorning" : 13,                     "closingMorning" : 14             }     ] } 

A current time of 12 would match the first but not the second document but a value of 13 would match both.

Also noting that these are within an array so given your estimated purpose you probably want a "dayOfWeek" field to include in there as well

like image 158
Neil Lunn Avatar answered Oct 24 '22 07:10

Neil Lunn