hh54188
hh54188

Reputation: 15656

MongoDB: how to insert document without repeat

Suppose I already have some data in database:

{
   id: 001,
   title: "title_1"
}
{
   id: 002,
   title: "title_2"
}
{
   id: 003,
   title: "title_3"
}

then I want to insert some new documents:

{
   id: 003    // id repeat
   title: "title_4"
}
{
   id: 004
   title: "title_5"
}

but I don't want to insert the { id:003 } item, because some guy in the database already has the same id.

So, how can I let the MongoDB ignore the repeat value(with specified key) item when I insert new data?

Upvotes: 1

Views: 1267

Answers (3)

Salvador Dali
Salvador Dali

Reputation: 222969

Apart from putting this as unique index as it was suggested earlier, you can just insert them with a different key. Instead of id key as you already have, you can insert them with unique primary key _id (you can use your own unique _id field if you want so http://docs.mongodb.org/manual/core/document/#the-id-field)

Upvotes: 0

Jhanvi
Jhanvi

Reputation: 5149

For this you have to create unique index on id. You have to try like this:

 db.collection.ensureIndex( { id: 1 }, { unique: true } )

Upvotes: 2

hope_is_grim
hope_is_grim

Reputation: 1934

I think you could use a Unique Index

Upvotes: 0

Related Questions