如何像在 SQL 中一样在 MongoDB 中正确使用"exist"函数?\
mongodbdatabasebig data analyticsmysql更新于 2025/9/12 0:44:17
要检查记录是否存在,请在 MongoDB 中使用 findOne()。让我们首先创建一个包含文档的集合 −
> db.existsAlternateDemo.insertOne({"StudentName":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e06d23f9e4dae213890ac5c")
}
> db.existsAlternateDemo.insertOne({"StudentName":"Chris","StudentAge":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e06d2559e4dae213890ac5d")
}
>db.existsAlternateDemo.insertOne({"StudentName":"Chris","StudentAge":22,"StudentCountryName":"US"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e06d2689e4dae213890ac5e")
}
以下是使用 find() 方法显示集合中的所有文档的查询 −
> db.existsAlternateDemo.find();
这将产生以下输出 −
{ "_id" : ObjectId("5e06d23f9e4dae213890ac5c"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5e06d2559e4dae213890ac5d"), "StudentName" : "Chris", "StudentAge" : 21 }
{ "_id" : ObjectId("5e06d2689e4dae213890ac5e"), "StudentName" : "Chris", "StudentAge" : 22, "StudentCountryName" : "US" }
以下是正确使用 MongoDB 中的 'exist' 函数的查询,类似于 SQL 中的 findOne() −
> db.existsAlternateDemo.findOne({"StudentCountryName" : "US"});
这将产生以下输出 −
{
"_id" : ObjectId("5e06d2689e4dae213890ac5e"),
"StudentName" : "Chris",
"StudentAge" : 22,
"StudentCountryName" : "US"
}
有用资源
mysql 参考教程 - 该教程包含有关 mysql 的更多信息:https://www.cainiaomax.com/mysql/

