Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to exclude a mongo document if current date is in between any dates available in array of startDate and endDate array of objects in MongoDB

I’ve a schema something like this, where I got an array of startDate and endDate in the form of array of objects. Please find the screenshot below.

enter image description here

Now I need to check if current date is between any of the available dates range.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is what I been trying,

db.products.aggregate([
  {
    "$match": {
      "$and": [
        {
          "isDeleted": false
        },
        {
          "isArchived": false
        },
        {
            _id: ObjectId("63de4823561e0319a5745537")
        },
        {
            bookings: { 
                '$elemMatch': { 
                    $nin:[
                        {productBookingCompleteDate: { '$gt': new Date("2023-04-03T04:03:49.642Z") }}, 
                        {productBookingStartDate: { '$lt': new Date("2023-04-03T04:03:49.642Z") }}    
                    ]
                }
            }
        }
      ]
    }
  },
...... // Rest of the logics
])

but this is returning data if current date is falling between these range, but I want the opposite case. It should return document only if the current date is not in any date range.

can anyone please help me with this.

Thanks.

>Solution :

To exclude a MongoDB document if the current date is between any dates available in an array of startDate and endDate objects, you can use the $elemMatch operator to check if there is any booking range that includes the current date. Then, you can negate the match using the $not operator to return only those documents where the current date is not within any booking range.

db.products.find({
  _id: ObjectId("63de4823561e0319a5745537"),
  isDeleted: false,
  isArchived: false,
  bookings: {
    $not: {
      $elemMatch: {
        productBookingStartDate: { $lte: new Date() },
        productBookingCompleteDate: { $gte: new Date() }
      }
    }
  }
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading