user4951
user4951

Reputation: 33080

How to keep 2 "columns" in mongodb unique

I am merging business databases.

So I have data like

id1 id2 
id1 id2
id1 id4
id1 id5
id1 id2
id4 id5
id4 id5
id4 id5
id4 id5

That sort of thing.

I want to sort that into

id1 id2
id1 id4
id1 id5
id1 id2
id4 id5

So basically if first column and the second column is the same than it's duplicate

Do I need duplicate or just compound indexes with unique attribute will suffice? If so what would be the format of the index.

Upvotes: 3

Views: 685

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230326

Yes, I think a unique compound index will do.

db.collection.ensureIndex({first_column: 1, second_column: 1}, {unique: true});

UPDATE: Deprecated since version 3.0.0: db.collection.ensureIndex() is now an alias for db.collection.createIndex(). Use db.collection.createIndex() rather than db.collection.ensureIndex() to create new indexes.

Upvotes: 6

Related Questions