Javascript 我可以按日期查询 MongoDB ObjectId 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8749971/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:20:13  来源:igfitidea点击:

Can I query MongoDB ObjectId by date?

javascriptmongodb

提问by Zach

I know that ObjectIds contain the date they were created on. Is there a way to query this aspect of the ObjectId?

我知道 ObjectIds 包含它们的创建日期。有没有办法查询ObjectId的这个方面?

回答by Leftium

Popping Timestamps into ObjectIdscovers queries based on dates embedded in the ObjectId in great detail.

Popping Timestamps into ObjectIds涵盖了基于嵌入在 ObjectId 中的日期的非常详细的查询。

Briefly in JavaScript code:

在 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') } });

回答by radtek

In pymongo, it can be done this way:

在 中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}}))

回答by jksdua

Using inbuilt function provided by mongodb drivers in in Node.js lets you query by any timestamp:

在 Node.js 中使用 mongodb 驱动程序提供的内置函数可以让您按任何时间戳查询:

var timestamp = Date.now();
var objectId = ObjectID.createFromTime(timestamp / 1000);

Alternatively, to search for records before the current time, you can simply do:

或者,要搜索当前时间之前的记录,您只需执行以下操作:

var objectId = new ObjectID(); // or ObjectId in the mongo shell

Source: http://mongodb.github.io/node-mongodb-native/api-bson-generated/objectid.html

来源:http: //mongodb.github.io/node-mongodb-native/api-bson-generated/objectid.html

回答by atp

Since the first 4 bytes of an ObjectId represent a timestamp, to query your collection chronologically, simply order by id:

由于 ObjectId 的前 4 个字节表示时间戳,要按时间顺序查询您的集合,只需按 id 排序:

# oldest first; use pymongo.DESCENDING for most recent first
items = db.your_collection.find().sort("_id", pymongo.ASCENDING)

After you get the documents, you can get the ObjectId's generation timelike so:

获取文档后,您可以像这样获取 ObjectId 的生成时间

id = some_object_id
generation_time = id.generation_time

回答by Karthickkumar Nagaraj

how to find Find the Command (this date[2015-1-12] to this Date[2015-1-15]):

如何找到查找命令(这个日期[2015-1-12]到这个日期[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()

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()

Count the Command (this date[2015-1-12] to this Date[2015-1-15]):

计算命令(这个日期[2015-1-12]到这个日期[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")}})

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")}})

Remove the Command (this date[2015-1-12] to this Date[2015-1-15]):

删除命令(这个日期[2015-1-12]到这个日期[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")}})

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")}})

回答by Sagar Veeram

You can use $convertfunction to extract the date from ObjectId starting in 4.0 version.

$convert从 4.0 版本开始,您可以使用函数从 ObjectId 中提取日期。

Something like

就像是

$convert: { input: "$_id", to: "date" } 

You can query on date comparing between start and end time for 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")]}
    ]
  }
})

OR

或者

You can use shorthand $toDateto achieve the same.

您可以使用速记$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")]}
    ]
  }
})

回答by Murali

To get last 60 days old documents in mongo collection i used below query in shell.

为了在 mongo 集合中获取过去 60 天的旧文档,我在 shell 中使用了以下查询。

db.collection.find({_id: {$lt:new ObjectId( Math.floor(new Date(new Date()-1000*60*60*24*60).getTime()/1000).toString(16) + "0000000000000000" )}})

回答by AbdelHady

If you want to make a range query, you can do it like in this post. For example querying for a specific day (i.e. Apr 4th 2015):

如果你想进行范围查询,你可以像这篇文章中那样做。例如查询特定日期(即 2015 年 4 月 4 日):

> var objIdMin = ObjectId(Math.floor((new Date('2015/4/4'))/1000).toString(16) + "0000000000000000")
> var objIdMax = ObjectId(Math.floor((new Date('2015/4/5'))/1000).toString(16) + "0000000000000000")
> db.collection.find({_id:{$gt: objIdMin, $lt: objIdMax}}).pretty()

回答by Gianluca

From the documentation:

从文档:

o = new ObjectId()
date = o.getTimestamp()

this way you have date that is a ISODate.

这样你就有了一个 ISODate 的日期。

Look at http://www.mongodb.org/display/DOCS/Optimizing+Object+IDs#OptimizingObjectIDs-Extractinsertiontimesfromidratherthanhavingaseparatetimestampfield. for more information

查看 http://www.mongodb.org/display/DOCS/Optimizing+Object+IDs#OptimizingObjectIDs-Extractinsertiontimesfromidratherthanhaveaseparatetimestampfield。想要查询更多的信息

回答by Yogesh

Using MongoObjectID you should also find results as given below

使用 MongoObjectID 您还应该找到如下所示的结果

db.mycollection.find({ _id: { $gt: ObjectId("5217a543dd99a6d9e0f74702").getTimestamp().getTime()}});