MongoDB:如何插入文档而无需重复 [英] MongoDB: how to insert document without repeat

查看:52
本文介绍了MongoDB:如何插入文档而无需重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我已经在数据库中有一些数据:

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"
}

但是我不想插入 {id:003} 项,因为数据库中的某个家伙已经具有相同的ID.

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

那么,当我插入新数据时,如何让MongoDB忽略重复值(具有指定键)项?

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

推荐答案

为此,您必须在 id 上创建唯一索引.您必须尝试这样:

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

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

这篇关于MongoDB:如何插入文档而无需重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆