如何在MongoDB中创建嵌套索引?
要在MongoDB中创建嵌套索引,可以使用createIndex()
或ensureIndex()
。语法如下-
db.yourCollectionName.createIndex({"yourOuterFieldName.yourInnerFieldName.yourSecondInnerFieldName": 1});
为了理解语法,让我们用文档创建一个集合。使用文档创建集合的查询如下-
> db.nestedIndexDemo.insertOne(... {
...
... "CustomerId":101,
... "CustomerDetails":
... {
... "CustomerListDetails":
... {
... "CustomerName":"Larry",
... "CustomerProjectName": "Project-1",
... "CustomerCountryName":"US"
... }
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8fc565d3c9d04998abf010")
}
在find()
method的帮助下显示集合中的所有文档。查询如下-
> db.nestedIndexDemo.find().pretty();
以下是输出-
{"_id" : ObjectId("5c8fc565d3c9d04998abf010"),
"CustomerId" : 101,
"CustomerDetails" : {
"CustomerListDetails" : {
"CustomerName" : "Larry",
"CustomerProjectName" : "Project-1",
"CustomerCountryName" : "US"
}
}
}
这是在MongoDB中创建嵌套索引的查询:
> db.nestedIndexDemo.createIndex({"CustomerDetails.CustomerListDetails.CustomerCountryName": 1});{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
这是显示索引的查询-
> db.nestedIndexDemo.getIndexes();
以下是输出-
[{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "test.nestedIndexDemo"
},
{
"v" : 2,
"key" : {
"CustomerDetails.CustomerListDetails.CustomerCountryName" : 1
},
"name" : "CustomerDetails.CustomerListDetails.CustomerCountryName_1",
"ns" : "test.nestedIndexDemo"
}
]
以上是 如何在MongoDB中创建嵌套索引? 的全部内容, 来源链接: utcz.com/z/341204.html