1

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?

3
  • If it is okay to overwrite (but not add a new record) save works. Do you not want to overwrite? Commented Oct 31, 2013 at 8:35
  • @PaulDraper: Overwrite is Ok Commented Oct 31, 2013 at 9:15
  • It would be helpful if you would provide your expected final collection results. Commented Oct 31, 2013 at 11:16

3 Answers 3

2

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

 db.collection.ensureIndex( { id: 1 }, { unique: true } )
Sign up to request clarification or add additional context in comments.

Comments

0

I think you could use a Unique Index

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.