从包含文档的 MongoDB 集合中评估一个或多个值

mongodbdatabasebig data analytics更新于 2026/1/11 13:52:17

要评估一个或多个值,请使用 $or 和 find() 函数。让我们创建一个包含文档的集合 −

> db.demo174.insertOne({"StudentName":"Chris","CountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e383c709e4f06af551997e5")
}
> db.demo174.insertOne({"StudentName":"David","CountryName":"UK"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e383c779e4f06af551997e6")
}
> db.demo174.insertOne({"StudentName":"Bob","CountryName":"AUS"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e383c7e9e4f06af551997e7")
}

借助 find() 方法显示集合中的所有文档 −

> db.demo174.find();

这将产生以下输出 −

{ "_id" : ObjectId("5e383c709e4f06af551997e5"), "StudentName" : "Chris", "CountryName" : "US" }
{ "_id" : ObjectId("5e383c779e4f06af551997e6"), "StudentName" : "David", "CountryName" : "UK" }
{ "_id" : ObjectId("5e383c7e9e4f06af551997e7"), "StudentName" : "Bob", "CountryName" : "AUS" }

以下查询用于评估一个或多个值。这里,我们获取多个值,例如学生"David"或国家"US"。 −

> db.demo174.find({$or:[{"StudentName":"David"},{"CountryName":"US"}]});

这将产生以下输出 −

{ "_id" : ObjectId("5e383c709e4f06af551997e5"), "StudentName" : "Chris", "CountryName" : "US" }
{ "_id" : ObjectId("5e383c779e4f06af551997e6"), "StudentName" : "David", "CountryName" : "UK" }

相关文章