开发者

MongoDB indexes

I'm in the process of conver开发者_如何学Pythonting my Rails app to use mongodb through mongoid. I have two questions relating to indexes. I think I know the answer, but I want confirmation from someone who has more experience with mongodb.

Let's look at the following example where I have one relational association between Users and Posts.

user.rb

class User  
    has_many_related :posts  
end

post.rb

class Post  
    belongs_to_related :user  
end

Now when I look at the indexes created through the MongoHQ interface, I notice the following two:

  1. Key Name: _id_

    Indexed Field: _id

    Unique: <blank>

    Is the id guaranteed to be unique? If so, why isn't unique set. If not, how can I set this and do I need to?

  2. Key Name: user_id_1

    Indexed Field: user_id

    Unique: false

    Am I correct in assuming the Indexed Field is the field name in the collection? Just want to confirm as Key Name has the _1 after it.


Yes, _id in MongoDB is always unique. It's the primary key, which is why setting UNIQUE isn't necessary.


Here is very clearly described indexes in MongoDB Indexing Overview.

_id

The _id index is a unique index** on the _id field, and MongoDB creates this index by default on all collections. You cannot delete the index on _id.

The _id field is the primary key for the collection, and every document must have a unique _id field. You may store any unique value in the _id field. The default value of _id is ObjectID on every insert()

** Although the index on _id is unique, the getIndexes() method will not print unique: true in the mongo shell.


If you do not specify the _id value manually in MongoDB, then the type will be set to a special BSON datatype that consists of a 12-byte binary value.

The 12-byte value consists of a 4-byte timestamp, a 3-byte machine id, a 2-byte process id, and a 3-byte counter. Due to this design, this value has a resonably high probability of being unique.

Reference: The Definitive Guide to MongoDB: The NoSQL Database for Cloud and Desktop Computing (book)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜