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

복합 다중 키 인덱스를 사용하기 위해 컬렉션을 인덱싱하는 방법은 무엇입니까?

<시간/>

이를 위해sureIndex()를 사용하십시오. 문서로 컬렉션을 만들자 −

> db.demo678.ensureIndex({id:1,"details.userId":1});
{
   "createdCollectionAutomatically" : true,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}
> db.demo678.insertOne(
...    {
...       id:101,
...
...       "details" : [
...          {
...             "userId" : "1001",
...             "userName":"Chris"
...          },
...          {
...             "userId" : "1002",
...             "userName":"David"
...          }
...       ],
...       "otherDetails" : [
...          {
...             CountryName:"US",
...             EmailId:["Chris@gmail.com","David@gmail.com"]
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea4276904263e90dac943fc")
}

find() 메서드를 사용하여 컬렉션의 모든 문서 표시 -

> db.demo678.find();

이것은 다음과 같은 출력을 생성합니다 -

{ "_id" : ObjectId("5ea4276904263e90dac943fc"), "id" : 101, "details" : [
   { "userId" : "1001", "userName" : "Chris" },
   { "userId" : "1002", "userName" : "David" }
], "otherDetails" : [
   { "CountryName" : "US", "EmailId" : [ "Chris@gmail.com", "David@gmail.com" ] }
] }