如何使我的集合索引使用複合多鍵索引?


為此,請使用 ensureIndex()。讓我們建立一個帶有文件的集合 −

> 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" ] }
] }

更新於: 14-May-2020

62 次瀏覽

開啟你的 職業

完成課程,獲得認證

開始
廣告
© . All rights reserved.