หากต้องการค้นหาเอกสารใน MongoDB ด้วย _id คุณต้องเรียก ObjectId() ให้เราดูไวยากรณ์ก่อน
db.yourCollectionName.find({"_id":ObjectId("yourId")}).pretty(); เพื่อให้เข้าใจแนวคิดและค้นหาเอกสาร ให้เราใช้แบบสอบถามต่อไปนี้เพื่อสร้างคอลเลกชันที่มีเอกสาร
> db.searchDocumentDemo.insertOne({"UserId":1,"UserName":"Larry"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c97a8e4330fd0aa0d2fe487")
}
> db.searchDocumentDemo.insertOne({"UserId":2,"UserName":"Mike"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c97a8ea330fd0aa0d2fe488")
}
> db.searchDocumentDemo.insertOne({"UserId":3,"UserName":"David"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c97a8f1330fd0aa0d2fe489")
}
> db.searchDocumentDemo.insertOne({"UserId":4,"UserName":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c97a8fa330fd0aa0d2fe48a")
}
> db.searchDocumentDemo.insertOne({"UserId":5,"UserName":"Robert"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c97a901330fd0aa0d2fe48b")
}
> db.searchDocumentDemo.insertOne({"UserId":6,"UserName":"Sam"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c97a911330fd0aa0d2fe48c")
} ต่อไปนี้เป็นแบบสอบถามเพื่อแสดงเอกสารทั้งหมดจากคอลเลกชันโดยใช้วิธี find()
> db.searchDocumentDemo.find().pretty();
This will produce the following output:
{
"_id" : ObjectId("5c97a8e4330fd0aa0d2fe487"),
"UserId" : 1,
"UserName" : "Larry"
}
{
"_id" : ObjectId("5c97a8ea330fd0aa0d2fe488"),
"UserId" : 2,
"UserName" : "Mike"
}
{
"_id" : ObjectId("5c97a8f1330fd0aa0d2fe489"),
"UserId" : 3,
"UserName" : "David"
}
{
"_id" : ObjectId("5c97a8fa330fd0aa0d2fe48a"),
"UserId" : 4,
"UserName" : "Chris"
}
{
"_id" : ObjectId("5c97a901330fd0aa0d2fe48b"),
"UserId" : 5,
"UserName" : "Robert"
}
{
"_id" : ObjectId("5c97a911330fd0aa0d2fe48c"),
"UserId" : 6,
"UserName" : "Sam"
} ต่อไปนี้เป็นแบบสอบถามเพื่อค้นหาเอกสารใน MongoDB โดย _id เราเรียก ObjectId() เพื่อแสดงผลลัพธ์:
> db.searchDocumentDemo.find({"_id":ObjectId("5c97a901330fd0aa0d2fe48b")}).pretty(); สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้:
{
"_id" : ObjectId("5c97a901330fd0aa0d2fe48b"),
"UserId" : 5,
"UserName" : "Robert"
}