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

Projection ของ Array ดึง Element แรกใน MongoDB

การ Projection Array เพื่อดึง Element แรก

หากต้องการ Element แรกจาก Array สามารถใช้ $slice ร่วมกับ $gte

สร้าง Collection พร้อมข้อมูล

> db.demo640.insertOne({Name:"John","Scores":[80,90,75]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e9c2eb86c954c74be91e6e0") }
> db.demo640.insertOne({Name:"Chris","Scores":[85,70,89]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e9c2ece6c954c74be91e6e1") }

แสดงเอกสารทั้งหมด

> db.demo640.find();

ผลลัพธ์:

{ "_id" : ObjectId("5e9c2eb86c954c74be91e6e0"), "Name" : "John", "Scores" : [ 80, 90, 75 ] }
{ "_id" : ObjectId("5e9c2ece6c954c74be91e6e1"), "Name" : "Chris", "Scores" : [ 85, 70, 89 ] }

คิวรี Projection ด้วย $slice

> db.demo640.find({Scores:{$gte:85}},{ "Scores": {$slice : 1}});

ผลลัพธ์:

{ "_id" : ObjectId("5e9c2eb86c954c74be91e6e0"), "Name" : "John", "Scores" : [ 80 ] }
{ "_id" : ObjectId("5e9c2ece6c954c74be91e6e1"), "Name" : "Chris", "Scores" : [ 85 ] }