如何索引MongoDB中的两个数组? [英] How do I index two arrays in MongoDB?

查看:638
本文介绍了如何索引MongoDB中的两个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

db.hello.ensureIndex({"array1":1, "array2":1})

MongoDB不允许这样做,因为他们说它可能会失控。但是,我知道我的数组永远不会超过3的长度。我怎样才能破解MongoDB以允许一次索引多个数组?

MongoDB does not allow that, because they say "it can get out of hand". However, I know that my arrays will never exceed length of 3. How can I hack MongoDB to allow indexing multiple arrays at once?


使用复合索引,最多
任何文档中的一个索引值
可以是一个数组。因此,如果我们在{a:1,b:1}上有
索引,则以下
文件都可以:

When using a compound index, at most one of indexed values in any document can be an array. So if we have an index on {a: 1, b: 1}, the following documents are both fine:

{a: [1,2],b:1} {a:1,b:[1,2]}
但是,这个文件将无法插入
,并显示错误消息
无法索引并行数组:

{a: [1, 2], b: 1} {a: 1, b: [1, 2]} This document, however, will fail to be inserted, with an error message "cannot index parallel arrays":

{a:[1,2],b:[1,2]}带有索引并行数组的问题
是那个
笛卡儿乘积中每个价值
的复合键必须是
索引,这很快就会失控

{a: [1, 2], b: [1, 2]} The problem with indexing parallel arrays is that each value in the cartesian product of the compound keys would have to be indexed, which can get out of hand very quickly.


推荐答案

对你的问题的简短回答是;你没有。您可以使用的唯一选项是将每个唯一对存储为单个数组元素。所以而不是:

The short answer to your question is; you don't. The only option available to you is to store the every unique pair as a single array element. So rather than :

{a:[1,2], b[8,9]}

您存储

{ab:[[1,8], [1,9], [2,8], [2,9]]}

显然这有一些缺点所以它确实取决于你的具体用例,这是否是一个合适的解决方法。我同意mongo不应该拒绝多个数组索引只是为了白痴校对。这是小/低基数数组的一个很好的功能。

Obviously this has a few downsides so it really depends on your specific usecase whether or not this is an appropriate workaround. I do agree however that mongo shouldn't reject multiple array indexes just for idiot proofing. It's a good feature for small/low cardinality arrays.

这篇关于如何索引MongoDB中的两个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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