Home > Blockchain >  Mongoose get all documents where date and number of weeks have current date
Mongoose get all documents where date and number of weeks have current date

Time:02-18

I have this type of documents in mongoDB.

{
     _id:620df4541571891a71dfa372
     user_id:61cc109f967b757d484fbf3b
     instrument_type:"binance"
     sub_instrument:"BTC/USDT"
     start_date:2022-02-17T00:00:00.000 00:00
     type_quantity:2
     prediction:"High"
     points:12
     price:null
     run_at:null
     createdAt:2022-02-17T07:08:04.633 00:00
     updatedAt:2022-02-17T07:08:04.633 00:00
}

Here I have "start_date" which is starting day. "type_quantity" which is number of weeks from start day.

Example: If "start_date" is 2022-02-17T00:00:00.000 00:00 and "type_quantity" is 2. Then, the dates per week will become 2022-02-17, 2022-02-24 and 2022-03-03. And If current date is one of these dates then, get this document.

CodePudding user response:

You can use $dateAdd in an aggregation query like this:

Note here only is necessary a $match stage with $expr to get documents where:

  • Current date ($$NOW) is greater or equal than $start_date.
  • Current date ($$NOW) is lower or equal than calculated date adding X weeks.

i.e. the date found is between $start_date and start_date X weeks.

db.collection.aggregate([
  {
    "$match": {
      "$expr": {
        "$and": [
          {
            "$gte": [
              "$$NOW",
              "$start_date"
            ]
          },
          {
            "$lte": [
              "$$NOW",
              {
                "$dateAdd": {
                  "startDate": "$start_date",
                  "unit": "week",
                  "amount": "$type_quantity"
                }
              }
            ]
          }
        ]
      }
    }
  }
])

Example here adding more documents.

  • Related