如何通过_id在MongoDB中查找记录?

为了在MongoDB中通过_id查找记录,可以使用以下语法

db.yourCollectionName.find({"_id":yourObjectId});

让我们创建包含文档的集合

> db.findRecordByIdDemo.insertOne({"CustomerName":"Larry","CustomerAge":26});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9dc2c875e2eeda1d5c3671")
}
> db.findRecordByIdDemo.insertOne({"CustomerName":"Bob","CustomerAge":20});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9dc2d175e2eeda1d5c3672")
}
> db.findRecordByIdDemo.insertOne({"CustomerName":"Carol","CustomerAge":22});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9dc2d775e2eeda1d5c3673")
}
> db.findRecordByIdDemo.insertOne({"CustomerName":"David","CustomerAge":24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9dc2e375e2eeda1d5c3674")
}

以下是查询以借助find()方法显示集合中的所有文档

> db.findRecordByIdDemo.find().pretty();

这将产生以下输出

{
   "_id" : ObjectId("5c9dc2c875e2eeda1d5c3671"),
   "CustomerName" : "Larry",
   "CustomerAge" : 26
}
{
   "_id" : ObjectId("5c9dc2d175e2eeda1d5c3672"),
   "CustomerName" : "Bob",
   "CustomerAge" : 20
}
{
   "_id" : ObjectId("5c9dc2d775e2eeda1d5c3673"),
   "CustomerName" : "Carol",
   "CustomerAge" : 22
}
{
   "_id" : ObjectId("5c9dc2e375e2eeda1d5c3674"),
   "CustomerName" : "David",
   "CustomerAge" : 24
}
Following is the query to find record by _id in MongoDB:
> db.findRecordByIdDemo.find({"_id":ObjectId("5c9dc2d175e2eeda1d5c3672")}).pretty();

这将产生以下输出

{
   "_id" : ObjectId("5c9dc2d175e2eeda1d5c3672"),
   "CustomerName" : "Bob",
   "CustomerAge" : 20
}