简体   繁体   中英

Is there a way to query documents in mongoDB/mongoose to match ALL objects in an array property WHERE the datetime is greater than a specified date

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.

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)}] } } )

Try:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM