具有$or中设置了多个条件的文档获取 MongoDB 代码是什么?


让我们创建一个存储文档的集合 -

> db.demo711.insertOne({Name:"John","Marks":75,Age:21,status:"Active"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea85c215d33e20ed1097b7e")
}
> db.demo711.insertOne({Name:"Chris","Marks":55,Age:22,status:"Active"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea85c2c5d33e20ed1097b7f")
}
> db.demo711.insertOne({Name:"Bob","Marks":45,Age:20,status:"Inactive"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea85c3e5d33e20ed1097b80")
}
> db.demo711.insertOne({Name:"David","Marks":85,Age:23,status:"Active"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea85c775d33e20ed1097b81")
}

使用 find() 方法显示集合中的所有文档 -

> db.demo711.find();

这将产生以下输出 -

{ "_id" : ObjectId("5ea85c215d33e20ed1097b7e"), "Name" : "John", "Marks" : 75, "Age" : 21, "status" : "Active" }
{ "_id" : ObjectId("5ea85c2c5d33e20ed1097b7f"), "Name" : "Chris", "Marks" : 55, "Age" : 22, "status" : "Active" }
{ "_id" : ObjectId("5ea85c3e5d33e20ed1097b80"), "Name" : "Bob", "Marks" : 45, "Age" : 20, "status" : "Inactive" }
{ "_id" : ObjectId("5ea85c775d33e20ed1097b81"), "Name" : "David", "Marks" : 85, "Age" : 23, "status" : "Active" }

以下是使用 $or 的 MongoDB 查询 -

> db.demo711.find( { $or: [ { Age: {$gte:23}}, {Marks:{$gt:80} }, {status: 'Inactive'} ] }) ;

这将产生以下输出 -

{ "_id" : ObjectId("5ea85c3e5d33e20ed1097b80"), "Name" : "Bob", "Marks" : 45, "Age" : 20, "status" : "Inactive" }
{ "_id" : ObjectId("5ea85c775d33e20ed1097b81"), "Name" : "David", "Marks" : 85, "Age" : 23, "status" : "Active" }

更新于: 14-May-2020

2K+ 查看

启动你的职业生涯

完成课程,获取认证

开始
广告