如何在 MongoDB 中查找 ObjectID 对应的文档?
mongodbdatabasebig data analytics更新于 2026/1/28 0:22:17
要在 MongoDB 中查找 ObjectID 对应的文档,请使用以下语法 −
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 − 这是在 MongoDB 中查找具有 ObjectId 的文档的查询。
> db.findDocumentWithObjectIdDemo.find({"_id":ObjectId("5c90e4704afe5c1d2279d69d")}).pretty();
以下是输出 −
{
"_id" : ObjectId("5c90e4704afe5c1d2279d69d"),
"UserName" : "Carol",
"UserAge" : 26,
"UserHobby" : [
"Learning",
"Photography"
]
}
案例 2 − 这是在 MongoDB 中查找具有 ObjectId 的另一个文档的查询。
查询如下 −
> db.findDocumentWithObjectIdDemo.find({"_id": ObjectId("5c90e4444afe5c1d2279d69c")}).pretty();
以下是输出 −
{
"_id" : ObjectId("5c90e4444afe5c1d2279d69c"),
"UserName" : "Mike",
"UserAge" : 23
}

