我知道 ObjectIds 包含它们的创建日期。有没有办法查询 ObjectId 的这个方面?
我可以按日期查询 MongoDB ObjectId 吗?
IT技术
javascript
mongodb
                    2021-01-28 20:54:57
                
                    
                
            
        6个回答
            Popping Timestamps into ObjectIds涵盖了基于嵌入在 ObjectId 中的日期的非常详细的查询。
简而言之,JavaScript 代码:
/* This function returns an ObjectId embedded with a given datetime */
/* Accepts both Date object and string input */
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
}
/* Find all documents created after midnight on May 25th, 1980 */
db.mycollection.find({ _id: { $gt: objectIdWithTimestamp('1980/05/25') } });
在 中pymongo,可以通过以下方式完成:
import datetime
from bson.objectid import ObjectId
mins = 15
gen_time = datetime.datetime.today() - datetime.timedelta(mins=mins) 
dummy_id = ObjectId.from_datetime(gen_time)
result = list(db.coll.find({"_id": {"$gte": dummy_id}}))
在 Node.js 中使用 mongodb 驱动程序提供的内置函数可以让您按任何时间戳查询:
var timestamp = Date.now();
var objectId = ObjectID.createFromTime(timestamp / 1000);
或者,要搜索当前时间之前的记录,您只需执行以下操作:
var objectId = new ObjectID(); // or ObjectId in the mongo shell
来源:http : //mongodb.github.io/node-mongodb-native/api-bson-generated/objectid.html
$convert从 4.0 版本开始,您可以使用函数从 ObjectId 中提取日期。
就像是
$convert: { input: "$_id", to: "date" } 
您可以查询日期的开始和结束时间之间的日期比较。
db.collectionname.find({
  "$expr":{
    "$and":[
      {"$gte":[{"$convert":{"input":"$_id","to":"date"}}, ISODate("2018-07-03T00:00:00.000Z")]},
      {"$lte":[{"$convert":{"input":"$_id","to":"date"}}, ISODate("2018-07-03T11:59:59.999Z")]}
    ]
  }
})
或者
您可以使用速记$toDate来实现相同的目的。
db.collectionname.find({
  "$expr":{
    "$and":[
      {"$gte":[{"$toDate":"$_id"}, ISODate("2018-07-03T00:00:00.000Z")]},
      {"$lte":[{"$toDate":"$_id"},ISODate("2018-07-03T11:59:59.999Z")]}
    ]
  }
})
如何找到查找命令(this date[2015-1-12]to this Date[2015-1-15]):
db.collection.find({
  _id: {
    $gt: ObjectId(Math.floor((new Date('2015/1/12'))/1000).toString(16) + "0000000000000000"), 
    $lt: ObjectId(Math.floor((new Date('2015/1/15'))/1000).toString(16) + "0000000000000000")
  }
}).pretty()
计算命令(这个date[2015-1-12]到这个Date[2015-1-15]):
db.collection.count({
  _id: {
    $gt: ObjectId(Math.floor((new Date('2015/1/12'))/1000).toString(16) + "0000000000000000"), 
    $lt: ObjectId(Math.floor((new Date('2015/1/15'))/1000).toString(16) + "0000000000000000")
  }
})
删除命令(thisdate[2015-1-12]到 this Date[2015-1-15]):
db.collection.remove({
  _id: {
    $gt: ObjectId(Math.floor((new Date('2015/1/12'))/1000).toString(16) + "0000000000000000"), 
    $lt: ObjectId(Math.floor((new Date('2015/1/15'))/1000).toString(16) + "0000000000000000")
  }
})
其它你可能感兴趣的问题