Avoid duplicate values and create composite primary key

3,986 views
Skip to first unread message

Balaji D

unread,
Apr 16, 2012, 10:02:17 AM4/16/12
to mongodb-user
Hi,

I am trying to insert json object in mongoDB. How can I ensure I am
not inserting duplicate record. MongoDb by itself creates a unique id.
If I want to restrict duplicate calues based on two columns (composite
primary key), how should I proceed with that.

regards,
Balaji D.

Martin Skøtt

unread,
Apr 16, 2012, 10:41:02 AM4/16/12
to mongod...@googlegroups.com
Most straightforward way is to create a unique index on the two properties - just like you would do in a RDBMS.

Martin 

Sam Millman

unread,
Apr 16, 2012, 10:41:13 AM4/16/12
to mongod...@googlegroups.com
You can create a unique compound index like so:

db.col.ensureIndex({'_id':1, 'somefield': 1}, {'unique': true})


--
You received this message because you are subscribed to the Google Groups "mongodb-user" group.
To post to this group, send email to mongod...@googlegroups.com.
To unsubscribe from this group, send email to mongodb-user...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/mongodb-user?hl=en.


Derick Rethans

unread,
Apr 16, 2012, 10:44:50 AM4/16/12
to mongodb-user

You will need to set a unique index on those field, for example with:

db.yourcollection.ensureIndex( { fieldname1: 1, fieldname2: 1 }, { unique: true } );

you can find some more information at
http://www.mongodb.org/display/DOCS/Indexes#Indexes-unique%3Atrue

cheers,
Derick

--
http://mongodb.org | http://derickrethans.nl
twitter: @derickr and @mongodb

Reply all
Reply to author
Forward
0 new messages