เพื่อป้องกันไม่ให้ MongoDB ส่งคืน Object ID ขณะค้นหาเอกสาร คุณต้องตั้งค่า _idto 0 ก่อน ให้เราสร้างคอลเลกชันที่มีเอกสาร
> db.preventObjectIdDemo.insertOne(
... {
...
... "StudentName" : "Chris",
... "StudentDetails" : [
... {
... "StudentTotalScore" : 540,
... "StudentCountryName" : "US"
... },
... {
... "StudentTotalScore" : 489,
... "StudentCountryName" : "UK"
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca20a9c66324ffac2a7dc63")
} ต่อไปนี้เป็นแบบสอบถามเพื่อแสดงเอกสารทั้งหมดจากคอลเลกชันโดยใช้วิธี find()
> db.preventObjectIdDemo.find().pretty();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้
{
"_id" : ObjectId("5ca20a9c66324ffac2a7dc63"),
"StudentName" : "Chris",
"StudentDetails" : [
{
"StudentTotalScore" : 540,
"StudentCountryName" : "US"
},
{
"StudentTotalScore" : 489,
"StudentCountryName" : "UK"
}
]
} ต่อไปนี้เป็นแบบสอบถามเพื่อป้องกันไม่ให้ MongoDB ส่งคืน Object ID เมื่อค้นหาเอกสาร
> db.preventObjectIdDemo.find({ _id: ObjectId("5ca20a9c66324ffac2a7dc63")},
{StudentDetails: { $slice: [0, 1] } ,'_id': 0} ).pretty(); ต่อไปนี้เป็นผลลัพธ์ที่มองไม่เห็น ObjectID
{
"StudentName" : "Chris",
"StudentDetails" : [
{
"StudentTotalScore" : 540,
"StudentCountryName" : "US"
}
]
}