Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

วิธีดึงอาร์เรย์ของ _id ใน MongoDB

ใน MongoDB ฟิลด์ _id เป็นฟิลด์ที่จำเป็นและทำหน้าที่เป็น Primary Key ทุกเอกสารที่จัดเก็บในคอลเลกชันต้องมี _id ที่ไม่ซ้ำกัน

รูปแบบคำสั่งสำหรับดึง _id หลายค่า

db.yourCollectionName.find({ _id : { $in : [value1, value2, value3, ...] } } );

ตัวอย่างการใช้งาน

สร้างคอลเลกชันและเพิ่มเอกสารตัวอย่าง:

> db.selectInWhereIdDemo.insertOne({"_id":23});
{ "acknowledged" : true, "insertedId" : 23 }
> db.selectInWhereIdDemo.insertOne({"_id":28});
{ "acknowledged" : true, "insertedId" : 28 }
> db.selectInWhereIdDemo.insertOne({"_id":45});
{ "acknowledged" : true, "insertedId" : 45 }
> db.selectInWhereIdDemo.insertOne({"_id":75});
{ "acknowledged" : true, "insertedId" : 75 }
> db.selectInWhereIdDemo.insertOne({"_id":85});
{ "acknowledged" : true, "insertedId" : 85 }
> db.selectInWhereIdDemo.insertOne({"_id":145});
{ "acknowledged" : true, "insertedId" : 145 }

แสดงเอกสารทั้งหมดด้วย find():

> db.selectInWhereIdDemo.find().pretty();
{ "_id" : 23 }
{ "_id" : 28 }
{ "_id" : 45 }
{ "_id" : 75 }
{ "_id" : 85 }
{ "_id" : 145 }

ดึงเฉพาะ _id ที่ต้องการ (23, 45, 85, 145):

> db.selectInWhereIdDemo.find({ _id : { $in : [23,45,85,145] } } );
{ "_id" : 23 }
{ "_id" : 45 }
{ "_id" : 85 }
{ "_id" : 145 }

สรุป

ใช้ operator $in ร่วมกับ find() เพื่อค้นหาเอกสารที่ _id ตรงกับค่าใดค่าหนึ่งในอาร์เรย์ที่ระบุ วิธีนี้เหมาะสำหรับการดึงข้อมูลเฉพาะรายการหลายรายการพร้อมกัน