The ObjectId
used as the default key in mongodb documents has embedded timestamp (calling objectid.generation_time returns a datetime object). So it is possible to use this generation time instead of keeping a separate creation timestamp? How will you be able to sort by creation time or query for the last N items efficiently using this embedded timestamp?
相关问题
- MongoDB can not create unique sparse index (duplic
- Spring Data MongoDB - lazy access to some fields
- Golang mongodb aggregation
- mySQL alter table on update, current timestamp
- How to convert from Timestamp to Mongo ObjectID
相关文章
- mongodb有没有什么办法禁止读取数据的时候进行缓存
- mongodb-aggregate聚合查询分组后如何获得多字段
- mongodb error: how do I make sure that your journa
- How to track MongoDB requests from a console appli
- MongoError: cannot infer query fields to set, path
- Pymongo $in Query Not Working
- django.core.exceptions.ImproperlyConfigured: '
- How to represent an array with mixed types
To query projects created within 7 days, I use below snippet:
and if you want to get items with specified fields:
it will return something like this:
PS: the software I use to connect to MongoDB is Robo 3T
Hope this will help you.
Yes, you can use the generation_time of BSON ObjectId for the purposes you want. So,
will return the last 10 created items. However, since the embedded timestamps have a one second precision, multiple items within any second are stored in the order of their creation.
From: http://www.mongodb.org/display/DOCS/Object+IDs#ObjectIDs-DocumentTimestamps
"sorting on an _id field that stores ObjectId values is roughly equivalent to sorting by creation time, although this relationship is not strict with ObjectId values generated on multiple systems within a single second."
I suppose since MongoDB ObjectId contain a timestamp, you can sort by 'created date' if you will sort by objectId:
And if you want last 30 created items you can use following query:
I am actualy not sure,i just suppose that ordering by _id should work as described above. I'll create some tests later.
Update:
Yes it is so. If you order by _id you will automatically order by _id created date. I've done small test in c#, mb someone interest in it:
See
http://www.mongodb.org/display/DOCS/Object+IDs#ObjectIDs-DocumentTimestamps
Likely doable however I would always prefer having a dedicated timestamp instead of relying on some such internals like timestamp somehow embedded in some object id.
The code to convert a DateTime to its corresponding timestamp with the c# driver is as follows:
More info here: http://www.danharman.net/2011/10/26/mongodb-ninjitsu-using-objectid-as-a-timestamp/