使用 MongoDB 的 OR 运算符找出值并格式化结果?


使用 $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 }

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

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

这将产生以下输出:

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

更新日期:01-Apr-2020

80 次浏览

开启您的 职业生涯

完成课程后获得认证

开始
广告
© . All rights reserved.