MongoDB: how to insert document without repeat

2019-08-08 10:09发布

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条回答
手持菜刀,她持情操
2楼-- · 2019-08-08 10:28

I think you could use a Unique Index

查看更多
\"骚年 ilove
3楼-- · 2019-08-08 10:41

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)

查看更多
干净又极端
4楼-- · 2019-08-08 10:42

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

 db.collection.ensureIndex( { id: 1 }, { unique: true } )
查看更多
登录 后发表回答