Search This Blog

Wednesday, December 25, 2013

Updating _ID document attribute in MongoDB

Important note: This article is in relation to online MongoDB course. For more information about the course and other posts describing its content please check my main page here: M101P: MongoDB for Developers course

The _id in MongoDB has a special meaning and is always present in every document. It is used as the primary key for the collection.

It doesn't have to be generated automatically. You can specify its value manually if you want.
 
> db.people.insert( { _id : "rado", var : 1} )
> db.people.find()
{ "_id" : "rado", "var" : 1 }

> db.people.insert( { _id : "top", var : 2} )
> db.people.find()
{ "_id" : "rado", "var" : 1 }
{ "_id" : "top", "var" : 2 }

> db.people.insert( { _id : "top", var : 2} )
E11000 duplicate key error index: students.people.$_id_  dup key: { : "top" }

> db.people.find()
{ "_id" : "rado", "var" : 1 }
{ "_id" : "top", "var" : 2 }

No comments:

Post a Comment