สำหรับสิ่งนี้ ให้ใช้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:["[email protected]","[email protected]"] ... } ... ] ... } ... ); { "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" : [ "[email protected]", "[email protected]" ] } ] }