简体   繁体   中英

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

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

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