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

ค้นหาเอกสารด้วย ObjectId ใน MongoDB

ใช้ ObjectId() ในเงื่อนไข find()

เพื่อค้นหาเอกสารเฉพาะรายการด้วย _id ให้ห่อค่า ObjectId ด้วยฟังก์ชัน ObjectId()

ไวยากรณ์

db.yourCollectionName.find({"_id":ObjectId("yourObjectIdValue")}).pretty();

ตัวอย่าง

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

> db.findDocumentWithObjectIdDemo.insertOne({"UserName":"Larry"});
> db.findDocumentWithObjectIdDemo.insertOne({"UserName":"Mike","UserAge":23});
> db.findDocumentWithObjectIdDemo.insertOne({"UserName":"Carol","UserAge":26,"UserHobby":["Learning","Photography"]});

ค้นหาด้วย ObjectId เฉพาะ

กรณีที่ 1: ค้นหา ObjectId 5c90e4704afe5c1d2279d69d

> db.findDocumentWithObjectIdDemo.find({"_id":ObjectId("5c90e4704afe5c1d2279d69d")}).pretty();

ผลลัพธ์:

{ 
    "_id" : ObjectId("5c90e4704afe5c1d2279d69d"), 
    "UserName" : "Carol", 
    "UserAge" : 26, 
    "UserHobby" : [ "Learning", "Photography" ] 
}

กรณีที่ 2: ค้นหา ObjectId 5c90e4444afe5c1d2279d69c

> db.findDocumentWithObjectIdDemo.find({"_id":ObjectId("5c90e4444afe5c1d2279d69c")}).pretty();

ผลลัพธ์:

{ "_id" : ObjectId("5c90e4444afe5c1d2279d69c"), "UserName" : "Mike", "UserAge" : 23 }