ใช้ insertMany() สำหรับเพิ่มเอกสารหลายรายการพร้อมกัน และ createIndex() (แทน ensureIndex) เพื่อเพิ่มประสิทธิภาพการค้นหา/อัปเดต สร้างคอลเลกชันและเพิ่มข้อมูลหลายรายการ:
> db.demo325.insertMany([
{ _id: 101, Name: "Chris", Age: 23 },
{ _id: 102, Name: "David", Age: 24 },
{ _id: 103, Name: "Bob", Age: 22 }
]);
{ "acknowledged" : true, "insertedIds" : [ 101, 102, 103 ] }
แสดงข้อมูล:
> db.demo325.find().pretty();
สร้างดัชนีบนฟิลด์ Name:
> db.demo325.createIndex({Name:1});
{ "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
แนวทางปฏิบัติที่ดี (Best Practices)
- insertMany(): เร็วกว่า insertOne() หลายรอบ เพราะส่ง network request เพียงครั้งเดียว
- Ordered vs Unordered:
insertMany(docs, {ordered: false})ทำได้เร็วกว่าและต่อเนื่องแม้มี error บางรายการ - Bulk Operations: ใช้
db.collection.bulkWrite()สำหรับผสมผสาน insert, update, delete หลายออปเปอเรชัน - Index: สร้างดัชนีบนฟิลด์ที่ใช้ query บ่อย (createIndex แทน ensureIndex)
- Write Concern: ปรับ w: 1 (default) หรือ w: "majority" ตามความต้องการความน่าเชื่อถือ