MongoDB唯一索引不起作用

编程入门 行业动态 更新时间:2024-10-24 22:19:28
本文介绍了MongoDB唯一索引不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一部分简单的代码,由于唯一的索引约束而不得不失败.但是,尽管有唯一的索引,但这两个对象都已添加到数据库中并可以查询.

I have a portion of simple code, that has to fail because of unique index constraint. But both of the objects are added to database and can be queried, in spite of unique index.

BasicDBObject typeUrlIndex = new BasicDBObject(); typeUrlIndex.put(FIELD_TYPE_URL, 1); BasicDBObject typeUrlIndexOptions = new BasicDBObject(); typeUrlIndexOptions.put("background", true); typeUrlIndexOptions.put("sparse", true); typeUrlIndexOptions.put("unique", true); typeUrlIndexOptions.put("dropDups", true); objects.ensureIndex(typeUrlIndex, typeUrlIndexOptions); // here I can check, that index is really created, and it is true. List<DBObject> indexes = objects.getIndexInfo(); BasicDBObject dbo1 = new BasicDBObject(FIELD_TYPE_URL, "aaa"); objects.save(dbo1); BasicDBObject dbo2 = new BasicDBObject(FIELD_TYPE_URL, "aaa"); objects.save(dbo2);

两个对象都被保存并获得不同的_id.

Both objects are saved and get different _id.

更新. 我发现了,怎么了.保存到数据库后,这两个对象都有自己的ID,但实际上第二个对象没有保存(即使输入给定的ID也无法查询).

Upd. I found, what's wrong. Both objects get their own id after saving to database, but actually second object is not saved (it cannot be queried, even by given id).

感谢araqnid,它给出了正确的答案.不幸的是,我没有足够的评分来投票.

Thanks to araqnid, that gave right answer. Unfortunately, I don't have enough rating to vote.

推荐答案

在新的会话中查找时,两个对象都同时显示吗?如果保存不安全,则即使服务器实际上拒绝了第二个保存,也可能返回上面代码中分配的ID.

Are both objects showing up when you look in a new session? If the saves are unsafe, they could be returning with an ID assigned in the code above, even though the server will actually reject the second one.

更多推荐

MongoDB唯一索引不起作用

本文发布于:2023-11-22 13:05:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617525.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不起作用   索引   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!