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

วิธีดึงสมาชิกเฉพาะจากอาร์เรย์ใน MongoDB

ใช้ $arrayElemAt ใน Stage $project ของ Aggregate Framework เพื่อดึงสมาชิกที่ตำแหน่งที่กำหนดจากอาร์เรย์

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

สร้างคอลเลกชัน getParticularElement:

> db.getParticularElement.insertOne({"InstructorName":"Larry","InstructorTechnicalSubject":["Java","C","C++","MongoDB","MySQL","SQL Server"]});
{ "acknowledged" : true, "insertedId" : ObjectId("5c7ee027559dd2396bcfbfb1") }

แสดงข้อมูล:

> db.getParticularElement.find().pretty();
{"_id" : ObjectId("5c7ee027559dd2396bcfbfb1"), "InstructorName" : "Larry", "InstructorTechnicalSubject" : [ "Java", "C", "C++", "MongoDB", "MySQL", "SQL Server" ] }

คำสั่ง Aggregate ดึงสมาชิกตำแหน่งที่ 3 (index 3 = สมาชิกตัวที่ 4):

> db.getParticularElement.aggregate([
... {
... $project:
... {
... ElementFromAnArray: 1,
... FourthElement: { $arrayElemAt: [ "$InstructorTechnicalSubject", 3 ] },
... }
... }
... ]);
{"_id" : ObjectId("5c7ee027559dd2396bcfbfb1"), "FourthElement" : "MongoDB" }