如何在 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