如何在 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() 方法來顯示集合中的所有文件。查詢如下 -
> 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"
}
]
廣告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP