Computer >> 컴퓨터 >  >> 프로그램 작성 >> MongoDB

MongoDB에서 중첩 인덱스를 만드는 방법은 무엇입니까?

<시간/>

MongoDB에서 중첩 인덱스를 생성하려면 createIndex() 또는sureIndex()를 사용할 수 있습니다. 구문은 다음과 같습니다 -

db.yourCollectionName.createIndex({"yourOuterFieldName.yourInnerFieldName.yourSecondInnerFieldName":1});

구문을 이해하기 위해 문서로 컬렉션을 만들어 보겠습니다. 문서로 컬렉션을 생성하는 쿼리는 다음과 같습니다 -

> db.nestedIndexDemo.insertOne( ... { ... ... "CustomerId":101, ... "CustomerDetails":... { ... "CustomerListDetails":... { .. . "고객 이름":"래리", ... "고객 프로젝트 이름":"프로젝트-1", ... "고객 국가 이름":"미국" ... } ... } ... }... );{ "승인됨":true, "insertedId":ObjectId("5c8fc565d3c9d04998abf010")}

find() 메서드를 사용하여 컬렉션의 모든 문서를 표시합니다. 쿼리는 다음과 같습니다 -

> db.nestedIndexDemo.find().pretty();

다음은 출력입니다 -

{ "_id" :ObjectId("5c8fc565d3c9d04998abf010"), "CustomerId" :101, "CustomerDetails" :{ "CustomerListDetails" :{ "CustomerName" :"Larry", "CustomerProjectName" :"Project-1", " CustomerCountryName" :"미국" } }}

다음은 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, " 키" :{ "CustomerDetails.CustomerListDetails.CustomerCountryName" :1 }, "name" :"CustomerDetails.CustomerListDetails.CustomerCountryName_1", "ns" :"test.nestedIndexDemo" }]