If I were building a blog I could use the blog title as the unique identifier and parse it through the URL. However, what if I wanted to use numbers. You know how twitter has www.twitter.com/username/statuses/9834542? Has anyone figured out a nice way of making this work? using "_id" is out of the question since it's way too long.
相关问题
- MongoDB can not create unique sparse index (duplic
- Spring Data MongoDB - lazy access to some fields
- Golang mongodb aggregation
- How to convert from Timestamp to Mongo ObjectID
- MongoDB Indexing: Multiple single-field vs single
相关文章
- 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 does Cassandra scale horizontally ?
As long as you can guarantee uniqueness, you're not constrained to using the default "_id" MongoDB supplies.
Therefore, it's down to you how you generate this number. If you'd like to store this number inside MongoDB, then you could store it in a separate collection and increment it for every new URL required.
Incrementing a field is achieved by using the
$inc
verb, or you may want to take a look at how MongoDB can atomically update or increment a value.I have solved this problem by creating collection 'sequence' with data:
I'm using Morhpia, so have DAO for it. But you can do it without Morhpia too. Idea is to use $atomic (probably it can be omitted due updateing 1 instance only) and $inc modifier operator.
Sequence
Method on SequenceDAO:
Depending on MongoDB configuration (one node only or master/slave or replica set) you have to use correct WriteConcern. Using REPLICATION_SAFE in one environment with one instance only causes infinite loop.
If you want to add a uniqueness constraint to your own field in MongoDB, use an index. Then you can use any hashing algorithm you want to generate the number and test it for uniqueness. The example in the MongoDB documentation is
which will prevent you from inserting documents with the same firstname AND lastname as another document.
More information is available in the documentation.
It can be done by using the findandmodify command.
Let's consider we have a special collection named
sequences
and we want to have a sequence for post numbers (namedpostid
), you could use code similar to this:This command will return atomically the updated (
new
) document together with status. Thevalue
field contains the returned document if the command completed successfully.Technically, the ID number is too large to shorten it. However, a tactic can be filled. That is passing from Hex to alphanumeric, thus reducing the number of characters to tulizar and looks more beautiful in the Url. I really served very well ... here is
Of course this technique uses the same id, mongo.