简体   繁体   中英

MongoDB aggregation with nested array of objects property with date

I have data something like this

{
  "_id": ObjectId("52ed12c144aecc4bf004d0b6"),
  "active": true,
  "name": "woslo",
 "specialDays": [
  {
  "_id": ObjectId("5f0576196198a715b0a72c14")
  "status": true
  "date": 2020-07-08T04:00:00.000+00:00
  },
  {
  "_id": ObjectId("5f05a3726198a715b0a72c94")
  "status": false
  "date": 2020-07-09T04:00:00.000+00:00
  }
 ]
}

I want to fetch records using this query

 db.serviceProviders.aggregate([ { $match: { specialDays: { $elemMatch: { $or: [ { $and: [ { date: model.date // 2020-07-09T06:00:00.000Z }, { status: true } ] }, { date: { $ne: model.date //2020-07-09T06:00:00.000Z } } ] } } } } ]);

Scenario is : if date is present in specialDays array and the status should be true, or date should not be in specialDays Object's array then fetch this record. But every time it's fetching the same record that is above even status is false or date is present in array. Would you please help me how to figure it out, I tried a lot of queries in Mongo compass aggregation with ISODate('2020-07-08') but still not working. Thank you Happy Coding.

Problem is with your $ne condition. If status is false, then your $ne condition is true. Since it is logical OR, you are getting the output.

How about this ?

db.collection.aggregate([
  {
    $match: {
      specialDays: {
        $elemMatch: {
          $or: [
            {
              $and: [
                {
                  date: new Date("2020-07-09T04:00:00.000+00:00")
                },
                {
                  status: true
                }
              ]
            },
            {
              date: {//Changes here
                $gte: new Date("2020-07-09T06:00:00.000+00:00"),
                $lte: new Date("2020-07-09T23:59:59.000+00:00")
              }
            }
          ]
        }
      }
    }
  }
])

OR

this

Another reason for your $ne condition is true because it satisfies your first array element in specialDays array

db.collection.aggregate([
  {
    $match: {
      specialDays: {
        $elemMatch: {
          $or: [
            {
              $and: [
                {
                  date: new Date("2020-07-09T04:00:00.000+00:00")
                },
                {
                  status: true
                }
              ]
            },
            {
              $and: [
                {
                  date: {
                    $ne: new Date("2020-07-09T04:00:00.000+00:00")
                  }
                },
                {
                  status: false
                }
              ]
            }
          ]
        }
      }
    }
  }
])

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