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

ดึงค่าฟิลด์เฉพาะใน MongoDB ด้วย $in Operator

เพื่อดึงค่าฟิลด์เฉพาะ ให้ใช้ตัวดำเนินการ $in ซึ่งจะเลือกเอกสารที่ค่าของฟิลด์เท่ากับค่าใดค่าหนึ่งในอาร์เรย์ที่ระบุ

สร้างคอลเลกชันพร้อมดัชนีและเอกสาร:

> db.indexesDemo.createIndex({"StudentFirstName":1}); 
{ "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } 
> db.indexesDemo.insertOne({"StudentFirstName":"John","StudentLastName":"Smith"}); 
{ "acknowledged" : true, "insertedId" : ObjectId("5e06de4d25ddae1f53b621dd") } 
> db.indexesDemo.insertOne({"StudentFirstName":"Chris","StudentLastName":"Brown"}); 
{ "acknowledged" : true, "insertedId" : ObjectId("5e06de5825ddae1f53b621de") } 
> db.indexesDemo.insertOne({"StudentFirstName":"John","StudentLastName":"Doe"}); 
{ "acknowledged" : true, "insertedId" : ObjectId("5e06de6725ddae1f53b621df") } 
> db.indexesDemo.insertOne({"StudentFirstName":"David","StudentLastName":"Miller"}); 
{ "acknowledged" : true, "insertedId" : ObjectId("5e06de7225ddae1f53b621e0") }

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

> db.indexesDemo.find();

ผลลัพธ์:

คำสั่งค้นหาด้วย $in และ Projection แสดงเฉพาะ StudentFirstName (ซ่อน _id และ StudentLastName):

> db.indexesDemo.find( 
... { StudentFirstName: { $in: [ "John", "David" ] } }, 
... { _id: 0, StudentLastName: 0 } 
... );

ผลลัพธ์ - ได้เฉพาะชื่อ John และ David: