MongoDB:具有稀疏值的唯一和稀疏复合索引 [英] MongoDB: Unique and sparse compound indexes with sparse values

查看:93
本文介绍了MongoDB:具有稀疏值的唯一和稀疏复合索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试存储以下链接:

I'm trying to store the following link:

URL = {
  hostname: 'i.imgur.com',
  webid: 'qkELz.jpg'
}

我希望在这两个字段上具有唯一且稀疏的复合索引,因为:

I want a unique and sparse compound index on these two fields because:

  1. hostnamewebid的组合应该是唯一的.
  2. webid将始终使用hostname进行查询.
  3. webid不必是全局唯一的.
  4. URL不需要Webid.
  1. A combination of hostname and webid should be unique.
  2. webid will always be queried with hostname.
  3. webid need not be globally unique.
  4. A URL need not have a webid.

但是,当我这样做时,出现以下错误:

However, when I do this, I get the following error:

MongoError: E11000 duplicate key error index: db.urls.$hostname_1_webid_1  dup key: { : "imgur.com", : null }

我想在复合索引的情况下,空值会被计数,而在常规索引中则不会.

I guess in the case of compound indexes, nulls are counted, whereas in regular indexes, they are not.

解决这个问题有什么办法吗?现在,我仅要分别索引hostnamewebid.

Any way out of this problem? For now I'm just going to index hostname and webid separately.

推荐答案

请记住,mongodb每次查询只能使用一个索引(它不会将索引连接在一起,从而可以更快地对具有单独索引的两个字段进行查询)

Keep in mind that mongodb can only use one index per query (it won't join indexes together to make a query on two fields that have separate indexes faster).

也就是说,如果要尝试检查唯一性,可以在插入之前通过应用程序进行查询(这只能部分解决问题,因为查询和插入之间存在间隙).

That said, if you want to try to check for uniqueness, you could do a query from the app before inserting (which only partially solves the problem, because there's a gap between when you query and when you insert).

您可能希望就已过滤索引的JIRA问题进行投票,这可能会帮助您解决用例: https://jira.mongodb.org/browse/SERVER-785

You might want to vote on this JIRA issue for filtered indexes, which will probably help your use case: https://jira.mongodb.org/browse/SERVER-785

这篇关于MongoDB:具有稀疏值的唯一和稀疏复合索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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