在 MongoDB 中使用 OR 运算符查找值并格式化结果?

mongodbdatabasebig data analytics更新于 2026/1/10 4:52:17

使用 $or 运算符获取值,并使用"pretty()"格式化结果。让我们创建一个包含文档的集合 −

> db.demo304.insertOne({"StudentName":"Chris","StudentAge":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4ea3ccf8647eb59e562034")
}
> db.demo304.insertOne({"StudentName":"David","StudentAge":22});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4ea3d7f8647eb59e562035")
}
> db.demo304.insertOne({"StudentName":"Mike","StudentAge":24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4ea3e2f8647eb59e562036")
}
> db.demo304.insertOne({"StudentName":"Carol","StudentAge":22});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4ea3eef8647eb59e562037")
}

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

> db.demo304.find();

这将产生以下输出 −

{ "_id" : ObjectId("5e4ea3ccf8647eb59e562034"), "StudentName" : "Chris", "StudentAge" : 23 }
{ "_id" : ObjectId("5e4ea3d7f8647eb59e562035"), "StudentName" : "David", "StudentAge" : 22 }
{ "_id" : ObjectId("5e4ea3e2f8647eb59e562036"), "StudentName" : "Mike", "StudentAge" : 24 }
{ "_id" : ObjectId("5e4ea3eef8647eb59e562037"), "StudentName" : "Carol", "StudentAge" : 22 }

以下是在 MongoDB 中使用 OR 运算符获取值的查询 −

> db.demo304.find({ $or: [{ "StudentName": "David" }, { "StudentAge":22} ] } ).pretty();

这将产生以下输出 −

{
   "_id" : ObjectId("5e4ea3d7f8647eb59e562035"),
   "StudentName" : "David",
   "StudentAge" : 22
}
{
   "_id" : ObjectId("5e4ea3eef8647eb59e562037"),
   "StudentName" : "Carol",
   "StudentAge" : 22
}

相关文章