Friday, October 25, 2013

MongoDB - usage of Primary Key

Like other databases MongoDB also uses primary keys to distinguish documents.
We can provide our own, otherwise MongoDB will create itself a primary key for each document. This key is a Object which consists of time-stamp and information about the machine which document created.

How to provide our own primary key

$connection = new Mongo( "10.100.0.128:27017" );
$db = $connection->selectDB("primary_key_blog");
$collection = $db->blog_collection;
$collection.insert({ _id: 1, author: "UdaraR", blog: "http://udarakr.blogspot.com" });

else we can just say,

$collection.insert({author: "UdaraR", blog: "http://udarakr.blogspot.com" });

If we read the document we stored back,
 $collection->findone( array( "author" => "UdaraR" ) );
You can see that MongoDB itself added the 12 bytes ObjectId.

The greatest thing in the second method is that you can extract created-time without storing it separately. You can simply use ObjectId.getTimestamp() method to get this done.
ObjectId("507c7f79bcf86cd7994f6c0e").getTimestamp();
Other than the above usage, as in all other databases the primary usage will be to query using the ObjectId.

$id = new MongoId("507c7f79bcf86cd7994f6c0e");
$collection->findone( array( "_id" => $id ) );
Keep in mind this is not equal to string "507c7f79bcf86cd7994f6c0e".

Other than findone, we can provide this ObjectId with find, remove, update etc.

Tried this sample on linux environment with the use of mongo driver.

No comments:

Post a Comment