หากต้องการค้นหาเอกสารที่มี Objectid ใน MongoDB ให้ใช้ไวยากรณ์ต่อไปนี้ -
db.yourCollectionName.find({"_id":ObjectId("yourObjectIdValue")}).pretty(); เพื่อให้เข้าใจไวยากรณ์ข้างต้น ให้เราสร้างคอลเลกชันด้วยเอกสาร แบบสอบถามเพื่อสร้างคอลเลกชันที่มีเอกสารมีดังนี้ -
> db.findDocumentWithObjectIdDemo.insertOne({"UserName":"Larry"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c90e4384afe5c1d2279d69b")
}
> db.findDocumentWithObjectIdDemo.insertOne({"UserName":"Mike","UserAge":23});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c90e4444afe5c1d2279d69c")
}
> db.findDocumentWithObjectIdDemo.insertOne({"UserName":"Carol","UserAge":26,"UserHobby":["Learning","Photography"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c90e4704afe5c1d2279d69d")
} แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้เมธอด find() แบบสอบถามมีดังนี้ −
> db.findDocumentWithObjectIdDemo.find().pretty();
ต่อไปนี้เป็นผลลัพธ์ -
{ "_id" : ObjectId("5c90e4384afe5c1d2279d69b"), "UserName" : "Larry" }
{
"_id" : ObjectId("5c90e4444afe5c1d2279d69c"),
"UserName" : "Mike",
"UserAge" : 23
}
{
"_id" : ObjectId("5c90e4704afe5c1d2279d69d"),
"UserName" : "Carol",
"UserAge" : 26,
"UserHobby" : [
"Learning",
"Photography"
]
} กรณีที่ 1 - นี่คือแบบสอบถามเพื่อค้นหาเอกสารที่มี ObjectId ใน MongoDB
> db.findDocumentWithObjectIdDemo.find({"_id":ObjectId("5c90e4704afe5c1d2279d69d")}).pretty(); ต่อไปนี้เป็นผลลัพธ์ -
{
"_id" : ObjectId("5c90e4704afe5c1d2279d69d"),
"UserName" : "Carol",
"UserAge" : 26,
"UserHobby" : [
"Learning",
"Photography"
]
} กรณีที่ 2 - นี่คือแบบสอบถามเพื่อค้นหาเอกสารอื่นที่มี ObjectId ใน MongoDB
แบบสอบถามมีดังนี้ −
> db.findDocumentWithObjectIdDemo.find({"_id": ObjectId("5c90e4444afe5c1d2279d69c")}).pretty(); ต่อไปนี้เป็นผลลัพธ์ -
{
"_id" : ObjectId("5c90e4444afe5c1d2279d69c"),
"UserName" : "Mike",
"UserAge" : 23
}