如何在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"
}
]热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语