我注意到,对于索引Arrays,MongoDB文档表明Multikeys是应该使用的。但是,它没有说明将多个键显式创建为索引的任何内容。看起来好像这是自动的。那是对的吗?我不需要在数组元素上创建索引吗?我应该在父字段上创建索引吗?
http://www.mongodb.org/display/DOCS/Indexes#Indexes-IndexingArrayElements http://www.mongodb.org/display/DOCS/Multikeys
更新
我应该补充一点,我所说的数组包含嵌入式文档。以下是文档部分的具体示例:
{
_a: [{
_aid: "4e5d43698d3a329553111227",
_an: true
_aim: "http://graph.facebook.com/7403766/picture"
_ana: "Nick ONeill"
},
{
_aid: "4e5d43698d3a329553111228",
_an: true
_aim: "http://graph.facebook.com/129312401/picture"
_ana: "Joe Peterson"
}]
}
答案 0 :(得分:1)
数组字段的索引或包含数组字段的索引自动为多键索引。这意味着在索引中将有多个条目,一个用于数组的每个元素,一个用于整个数组。这允许匹配各个数组元素,如:
db.foo.find({myArrayField: "bar"})
将匹配以下文档:
{name: "whatever", myArrayField: ["foo", "bar", "baz"]}
查询这样的字段时,MongoDB确保任何给定的文档只返回一次,即使它多次匹配:
> db.foo.find({myArrayField: {$in: ["foo", "bar"]}})
{"name" : "whatever", "myArrayField" : [ "foo", "bar", "baz" ]}
编辑:您可以索引包含嵌入文档和“基本”类型的数组。执行此操作时,您可能希望使用$elemMatch
运算符搜索嵌入文档的部分匹配项:
(有关编辑的说明:我已更新示例以演示如何使用带有多个元素的$elemMatch
;当查询仅使用一个嵌入文档字段时,您不需要$elemMatch
)
> db.foo.save({name:"a", myArrayField: [{a:1, b:2}, {a:5, b:6}]})
> db.foo.save({name:"b", myArrayField: [{a:1, b:3}]})
> db.foo.save({name:"c", myArrayField: [{a:1, b:1}, {a:5, b:3}]})
> db.foo.find({myArrayField: {a: 1, b: 2}})
{name:"a", myArrayField: [{a:1, b:2}, {a:5, b:6}]}
> db.foo.find({myArrayField: {a: 1}})
// finds nothing, no document has a
// sub-document in myArrayField
// exactly equal to {a: 1}
> db.foo.find({"myArrayField.a": 1})
{name:"a", myArrayField: [{a:1, b:2}, {a:5, b:6}]}
{name:"b", myArrayField: [{a:1, b:3}]}
{name:"c", myArrayField: [{a:1, b:1}, {a:5, b:3}]}
> db.foo.find({myArrayFIeld: {$elemMatch: {a: 1, b: {$gt: 1}}}})
{name:"a", myArrayField: [{a:1, b:2}, {a:5, b:6}]}
{name:"b", myArrayField: [{a:1, b:3}]}
// this does not find document "b", since
// it does not have any sub-documents in
// myArrayField where a is 1 and b is
// greater than 1