PHP mongodb只插入唯一的值


php mongodb insert unique values only?

在mysql中,我可以设置唯一到我的表列,以便用户不会插入相同的值,如果该值已经存在,

CREATE TABLE IF NOT EXISTS `user` (
  `user_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `screen_name` varchar(255) DEFAULT NULL,
  `user_name` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `secret` varchar(255) NOT NULL,
  `salt` varchar(255) NOT NULL,
  `signature` varchar(255) NOT NULL,
  `visited_on` timestamp NOT NULL,
  PRIMARY KEY (`user_id`,`person_id`,`category_id`),
  UNIQUE KEY `user_name_UNIQUE` (`user_name`),
  UNIQUE KEY `salt_UNIQUE` (`salt`),
  UNIQUE KEY `signature_UNIQUE` (`signature`),
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

MongoDB呢?我怎样才能做到这一点呢?

$document = array(
    "title" => "Mr",
    "fullname" => "John C",
    "username" => "user1",
    "age" => 20
);
$collection->insert($document);

用户名为"user1"的用户重复,如果我再次运行它。对于MySQL,它不会发生,我会得到一个错误。但是,如果"user1"已经存在,我如何使Mongo抛出错误呢?

您的SQL表声明还声明了"user_name"字段上的"唯一"索引。因此,你想在MongoDB中做同样的事情,通过添加索引:

在shell中:

db.collection.createIndex({ "username": 1 },{ "unique": true })
或者在PHP代码中使用相同的方法:
$collection->createIndex(
    array( "username", 1 ),
    array( "unique", true )
)

如果你试图插入违反该约束的内容,那么你将收到一个异常。

如果你不想在每次插入操作中收到异常,那么你可以使用MongoDB的"upsert"功能以及 $setOnInsert 更新修饰符:

$document = array(
    "title" => "Mr",
    "fullname" => "John C",
    "username" => "user1",
    "age" => 20
);
$collection->update(
    array("username", $document["username"]),
    array('$setOnInsert',document),
    array("upsert", true)
)

只在创建新文档时进行更改,而不会修改已存在的查询字段值。

使用"upserts"当然要付出"查找"集合中的数据的代价,但是也可以在您打算修改与文档匹配的数据的操作中结合使用。

From mongodb doc

http://docs.mongodb.org/manual/tutorial/create-a-unique-index/

创建唯一索引¶

MongoDB允许在索引上指定唯一的约束。这些约束防止应用程序插入具有所插入字段重复值的文档。

MongoDB不能在指定的索引字段上创建唯一索引,如果集合中已经包含违反索引唯一约束的数据。

单个字段的唯一索引

要创建唯一索引,请考虑以下原型:

db.collection.createIndex( { a: 1 }, { unique: true } )