1. 程式人生 > >MongoDB 用時間篩選_id欄位

MongoDB 用時間篩選_id欄位

下面的程式碼來自stackoverflow,在MongoDB shell中執行


> function objectIdWithTimestamp(timestamp) {
     // Convert string date to Date object (otherwise assume timestamp is a date)
     if (typeof(timestamp) == 'string') {
         timestamp = new Date(timestamp);
     }
 
     // Convert date object to hex seconds since Unix epoch
     var hexSeconds = Math.floor(timestamp/1000).toString(16);
 
     // Create an ObjectId with that hex timestamp
     var constructedObjectId = ObjectId(hexSeconds + "0000000000000000");
 
     return constructedObjectId
 }
> db.digital_message.find({ _id: { $lt: objectIdWithTimestamp('2015/10/01') } }).count()
7792766
> db.digital_message.count()
7959508