Data type conversion in MongoDB

后端 未结 5 1233
离开以前
离开以前 2020-12-29 04:16

I have a collection called Document in MongoDB. Documents in this collection have a field called CreationDate stored in ISO date type. My task is to count the number of docu

5条回答
  •  被撕碎了的回忆
    2020-12-29 04:32

    FOR MONGO >= 3.0 (after ~2015)

    In case some poor souls stumble across this question in 2017, like me: As of Mongo 3.0 there is now a dateToString operator available

    which means if you have proper Date()'s you should be able to do simply:

    db.Document.aggregate( 
        , {$project: {_id:1, CreationDate:1}
        , {$group: {
             _id : { $dateToString: { format: "%Y-%m-$d", date: "$CreationDate" } },
             cnt:{$sum:1}}}
        , {$sort:{'cnt':-1}}
    );
    

    For those of us who happen to have dates stored in non-date field (what joy!) you can create a new Date() object in the project step. In my case, the date was stored as a number of milliseconds (integer) and I add the number of milliseconds to the 0-Date.

    db.Document.aggregate( 
        , {$project: {
             _id:1, 
             CreationDate: {"$add": [ new Date(0), "$CreatedOn" ]}
    }
        , {$group: {
             _id : { $dateToString: { format: "%Y-%m-$d", date: "$CreationDate" } },
             cnt:{$sum:1}}}
        , {$sort:{'cnt':-1}}
    );
    

提交回复
热议问题