如何在 MongoDB 中创建嵌套索引?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9730136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Create a nested index in MongoDB?
提问by Mr. Demetrius Michael
A. How do I index "nested" and all of it's values?
A. 如何索引“嵌套”及其所有值?
B. How do I index valuetwo?
B. 我如何索引 valuetwo?
{
id: 00000,
attrs: {
nested:{
value: value1,
valuetwo: value2,
}
}
}
I've looked here: http://www.mongodb.org/display/DOCS/Indexes, and the docs to my knowledge, aren't clear about indexing things that aren't nested.
我看过这里:http: //www.mongodb.org/display/DOCS/Indexes和据我所知的文档,不清楚索引非嵌套的东西。
回答by Bryan Migliorisi
You'd create them just as if you were creating an index on a top level field:
您可以像在顶级字段上创建索引一样创建它们:
db.collection.ensureIndex({"attrs.nested.value": 1})
You do need to explicitly create indexes on each field.
您确实需要在每个字段上显式创建索引。
回答by cianmce
A.to index all the properties in "nested" you will have to index them separately:
A.要索引“嵌套”中的所有属性,您必须分别对它们进行索引:
db.collection.createIndex({"attrs.nested.value": 1});
db.collection.createIndex({"attrs.nested.valuetwo": 1});
This can be done in one command with:
这可以在一个命令中完成:
db.collection.createIndexes([{"attrs.nested.value": 1}, {"attrs.nested.valuetwo": 1}]);
B.to index just "valuetwo":
B.仅索引“valuetwo”:
db.collection.createIndex({"attrs.nested.valuetwo": 1})
Use createIndexover ensureIndex as ensureIndex is Deprecated since version 3.0.0
使用createIndexover ensureIndex 因为 ensureIndex自版本 3.0.0 起已弃用
回答by Arun Pratap Singh
MongoDB automatically creates a multikey index if any indexed field is an array; you do not need to explicitly specify the multikey type.
如果任何索引字段是数组,MongoDB 会自动创建一个多键索引;您不需要显式指定多键类型。
This will work for both the scenario's db.coll.createIndex( { "addr.pin": 1 } )
这将适用于场景的 db.coll.createIndex( { "addr.pin": 1 } )
Scenario 1 nested OBJECTS
场景 1 嵌套对象
{
userid: "1234",
addr: {
pin:"455522"
}
},
{
userid: "1234",
addr: {
pin:"777777"
}
}
Scenario 2 nested Arrays
场景 2 嵌套数组
{
userid: "1234",
addr: [
{ pin:"455522" },
{ pin:"777777" },
]
}