Dhruv Aggarwal
Dhruv Aggarwal

Reputation: 53

FIlter based on array inside Object in mongodb

Hi i am using mongoose to create an object which has a field with type object. The object has two more fields start_date and end_date. Now i get a query which should filter out the records which don't conincide with any of the start_date to end_date period. That is (either query_end_date < start_date or query_start_date > end_date)

type : [{
            userId : {
                type : mongoose.Schema.ObjectId,
                required : true
            },
            startDate : {
                type : Date,
                required : true
            },
            endDate : {
                type : Date,
                required : true
            }   
        }]

Upvotes: 0

Views: 53

Answers (1)

user7896971
user7896971

Reputation:

You could make a query with the $gt and $lt operators and the syntax for querying array of nested documents:

async function Query(query_start_date, query_end_date){
  try{
    let users = await Model.find({ $or: [{ "field.startDate" : { $gt : query_end_date}} ,
                                   {"field.endDate" : { $lt : query_start_date}} });
    console.log(users);
  } catch(err){
    console.log("Error ", err);
  }

Reference

Upvotes: 1

Related Questions