Home > other >  I'm trying to find by week, but it only comes out as 0
I'm trying to find by week, but it only comes out as 0

Time:04-07

I'm trying to find by week, but it only comes out as 0. How can I add week as a new field?

20220220 int type is stored in yyyymmdd The week fields result is only 0

enter image description here

{'$addFields':{
     {'ymd':{'$convert':{
     'input':
     {'$concat':[
        {'$substr':['$yyyymmdd',0,4]},'-',
        {'$substr':['$yyyymmdd',4,2]},'-',
        {'$substr':['$yyyymmdd',6,2]}
      ]},
      'to':'string'
     }}
    }
}

{'$addFields':{
    {
      'week':{'$week':new Date("$ymd")}
    }
}

CodePudding user response:

Use $toLong

db.collection.aggregate([
  {
    "$addFields": {
      "ymd": {
        "$convert": {
          "input": {
            "$concat": [
              {
                "$substr": [ { "$toLong": "$yyyymmdd" }, 0, 4 ]
              },
              "-",
              {
                "$substr": [ { "$toLong": "$yyyymmdd" }, 4, 2 ]
              },
              "-",
              {
                "$substr": [ { "$toLong": "$yyyymmdd" }, 6, 2 ]
              }
            ]
          },
          "to": "string"
        }
      }
    }
  },
  {
    "$addFields": {
      "week": { "$week": { "$toDate": "$ymd" } }
    }
  }
])

https://mongoplayground.net/p/sMRNHF7Go0R

  • Related