MongoDB: how to insert document without repeat

2019-08-08 09:46发布

问题:

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?

回答1:

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

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


回答2:

I think you could use a Unique Index



回答3:

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)