Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb: Get Documents where ALL embedded Documents satisfy query

Tags:

mongodb

I have the following query:

db.MyData.find( { "SubItems.EndDate" : { $lte : new Date() } })

Which returns me any document in my data where one of its embedded SubItems EndDate is in the past, but how do I alter this to return me the document only if all of its SubItems satisfy the query

In the below example my original query would return both documents but I only want it to return the second one.

{
    "_id" : 1,
    "name" : "item1"
    "SubItems" : [
        {
            "EndDate": ISODate("2016-10-01T00:00:00.000Z"),
        },
        {
            "EndDate": ISODate("2016-04-01T00:00:00.000Z"),
        },
    ]
}
{
    "_id" : 2,
    "name" : "item2"
    "SubItems" : [
        {
            "EndDate": ISODate("2016-02-01T00:00:00.000Z"),
        },
        {
            "EndDate": ISODate("2016-03-01T00:00:00.000Z"),
        },
    ]
}
like image 714
CeejeeB Avatar asked Jan 28 '26 22:01

CeejeeB


1 Answers

After seeing this question

I managed to achieve what i needed with the following query:

edb.Bookings.find( { "ItineraryItems.EndDate" : { $not : {  $gt : new Date() } } })
like image 91
CeejeeB Avatar answered Jan 31 '26 15:01

CeejeeB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!