Title: Primary Keys
Author: Dariusz Górecki <darek.krk@gmail.com>

---

By default YiiMongoDbSuite will always use the `_id` field as a collection primary key.

> [information]
> MongoDB itself guarantee that `_id` field will be unique across collection.

# The `_id` field {#_id}

The `_id` field in a short is, be default an instance of `MongoID` class.

If you will do `echo $model->_id` you will see something like: `'4ced75e1eb4ae8ca44000000'`

This is basically, the textual representation of auto-generated by MongoDB _id field.

**But be aware that MongoID is not a string!**

*This will not find anything! `$model->findByPk('4ced75e1eb4ae8ca44000000');`*

To find an model with specified ID use:

`$model->findByPk(new MongoID('4ced75e1eb4ae8ca44000000'));`

> [information]
> ### You can put **any** value into an `_id` field
> MongoDB will auto populate _id field by MongoID objects **only when** it is set to `NULL` 

# Own defined Primary Key for collection {#ownpk}

You can define a own field to be used as a Primary Key for yours collection, see example:

~~~
[php]
class Client extends EMongoDocument
{
	// ...
	// Define primaryKey method:
	public function primaryKey()
	{
		return 'personal_number'; // Model field name, by default the _id field is used
	}

	// Now you can:
	// Client::model()->findByPk(1234); // personal_number == 1234
	// ...
}
~~~