如何在MongoDB中仅找到满足条件的单个文档?

要仅查找单个文档,请findOne()在MongoDB中使用。让我们创建一个包含文档的集合-

> db.demo116.insertOne({"EmployeeId":101,"EmployeeName":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2eff98d8f64a552dae635b")
}
> db.demo116.insertOne({"EmployeeId":102,"EmployeeName":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2eff9fd8f64a552dae635c")
}
> db.demo116.insertOne({"EmployeeId":103,"EmployeeName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2effa5d8f64a552dae635d")
}
> db.demo116.insertOne({"EmployeeId":102,"EmployeeName":"Mike"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2effb7d8f64a552dae635e")
}

find()方法的帮助下显示集合中的所有文档-

> db.demo116.find();

这将产生以下输出-

{ "_id" : ObjectId("5e2eff98d8f64a552dae635b"), "EmployeeId" : 101, "EmployeeName" : "John" }
{ "_id" : ObjectId("5e2eff9fd8f64a552dae635c"), "EmployeeId" : 102, "EmployeeName" : "Bob" }
{ "_id" : ObjectId("5e2effa5d8f64a552dae635d"), "EmployeeId" : 103, "EmployeeName" : "David" }
{ "_id" : ObjectId("5e2effb7d8f64a552dae635e"), "EmployeeId" : 102, "EmployeeName" : "Mike" }

以下是在MongoDB中仅查找单个文档的查询-

> db.demo116.findOne({"EmployeeId":102});

这将产生以下输出-

{
   "_id" : ObjectId("5e2eff9fd8f64a552dae635c"),
   "EmployeeId" : 102,
   "EmployeeName" : "Bob"
}