Home > Back-end >  Is there a way to query documents in mongoDB/mongoose to match ALL objects in an array property WHER
Is there a way to query documents in mongoDB/mongoose to match ALL objects in an array property WHER

Time:02-24

const CourseSchema = new Schema({
  course_name: {
    type: String,
    trim: true,
  },
  Course_Runs: [
    {
      run_id: {
        type: String,
      },
      // This field is for Teachers that are involved in the course run
      teachers: [{ type: Schema.Types.ObjectId, ref: "users" }],
      // Course Date Duration will be an inferred field from first session and last session
      Sessions: [{
          session_start_datetime: {
            type: Date,
          },
          session_end_datetime: {
            type: Date,
          },
       ]
   }]
}

Above is a snippet of the Schema

I want to be able to get documents where ALL Sessions object has a session_start_datetime greater than a specified date such as current date.

CodePudding user response:

YOURMODEL.find( { Sessions: { $all: [{session_start_datetime: {$gte: YOUR_DATE}] } } )

don't forget to pass YOUR_DATE in a correct Date format or it will not work.

example if your date is a string:

YOURMODEL.find( { Sessions: { $all: [{session_start_datetime: {$gte: new Date(YOUR_DATE)}] } } )

CodePudding user response:

Try model.find({'Course_Runs.Sessions.session_start_datetime': { $gt: current_date })

  • Related