convert iso date to timestamp in mongo query

后端 未结 3 773
夕颜
夕颜 2020-11-30 09:43

here is the query

[
    { 
        \"$project\": {
            \"formattedDate\": { 
                \"$dateToString\": { \"format\": \"%Y-%m-%d\", \"date\":         


        
相关标签:
3条回答
  • 2020-11-30 09:59

    Mongodb 4.0 has introduced $toLong aggregation which convert date to timestamp

    db.collection.aggregate([
      { "$project": {
        "createdAt": {
          "$toLong": "$createdAt"
        }
      }}
    ])
    

    You can try it here

    0 讨论(0)
  • 2020-11-30 10:08

    If you want to update timestamp. with the current date and time use the below query.

    db.getCollection('movie').update(
    {"applicationId":"2b5958d9629026491c30b42f2d5256fa8","type":"shortcut"},
    {$set : {userName:"vipin+testkm23052020@applozic.com",created_at: NumberLong(new Date()),"updated_at":NumberLong(new Date()),"docIndex":UUID()}}, {multi:true, upsert: false}
    )
    
    0 讨论(0)
  • 2020-11-30 10:13

    Use $subtract arithmetic aggregation operator with your Date as minuend and new Date("1970-01-01") as subtrahend.

    db.collection.aggregate(
      {
        $project: { "timestamp": { $subtract: [ "$createdAt", new Date("1970-01-01") ] } } 
      }
    );
    

    For document

    { "_id": 1, "createdAt": ISODate("2016-09-01T14:35:14.952Z") }
    

    the result is

    { "_id": 1, "timestamp": NumberLong("1472740514952") }
    

    If you want to group both by timestamp and (year, month, date) you can divide timestamp by the amount of milliseconds in a day, so that it will be unique for each day (and not for each millisecond)

    db.collection.aggregate(
      {
        $project: 
          {
            "timestampByDay":
              {
                $floor: 
                  {
                    $divide: 
                      [ 
                        { $subtract: [ "$createdAt", new Date("1970-01-01") ] }, 
                        24 * 60 * 60 * 1000 
                      ] 
                  }
              },
            "date": "$createdAt"
          }
      },
      {
        $group:
          {
            "_id": "$timestampByDay",
            "date": { $first: "$date" }
          }
      }
    );
    
    0 讨论(0)
提交回复
热议问题