检查 MongoDB 中是否存在文档?
mongodbdatabasebig data analytics更新于 2026/1/15 6:22:17
您可以使用 findOne() 来实现此目的。语法如下 −
db.yourCollectionName.findOne({yourFieldName: 'yourValue'});
让我们创建一个包含文档的集合 −
> db.checkExistingDemo.insertOne({"StudentName":"John"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cbdf90dac184d684e3fa265")
}
> db.checkExistingDemo.insertOne({"StudentName":"Carol"));
{
&"acknowledged" : true,
&"insertedId" : ObjectId("5cbdf912ac184d684e3fa266")
}
> db.checkExistingDemo.insertOne({"StudentName":"Sam"));
{
&"acknowledged" : true,
"insertedId" : ObjectId("5cbdf916ac184d684e3fa267")
}
> db.checkExistingDemo.insertOne({"StudentName":"Mike"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cbdf91bac184d684e3fa268")
}
使用 find() 方法显示集合中的所有文档 −
> db.checkExistingDemo.find().pretty();
这将产生以下输出 −
{ "_id" : ObjectId("5cbdf90dac184d684e3fa265"), "StudentName" : "John" }
{ "_id" : ObjectId("5cbdf912ac184d684e3fa266"), "StudentName" : "Carol" }
{ "_id" : ObjectId("5cbdf916ac184d684e3fa267"), "StudentName" : "Sam" }
{ "_id" : ObjectId("5cbdf91bac184d684e3fa268"), "StudentName" : "Mike" }
Following is the query to check existing document −
> db.checkExistingDemo.findOne({StudentName: 'Carol'});
这将产生以下输出 −
{ "_id" : ObjectId("5cbdf912ac184d684e3fa266"), "StudentName" : "Carol" }

