MongoDB:组合 AND 和 OR?


首先,我们创建一个带有文档的集合 −

> db.demo293.insertOne({FirstName:"Chris",LastName:"Brown",Age:24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4d45075d93261e4bc9ea32")
}
> db.demo293.insertOne({FirstName:"David",LastName:"Miller",Age:23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4d45265d93261e4bc9ea33")
}
> db.demo293.insertOne({FirstName:"John",LastName:"Smith",Age:24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4d45385d93261e4bc9ea34")
}
> db.demo293.insertOne({FirstName:"Adam",LastName:"Doe",Age:21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4d46cf5d93261e4bc9ea35")
}

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

> db.demo293.find();

这将产生以下输出 −

{ "_id" : ObjectId("5e4d45075d93261e4bc9ea32"), "FirstName" : "Chris", "LastName" : "Brown", "Age" : 24 }
{ "_id" : ObjectId("5e4d45265d93261e4bc9ea33"), "FirstName" : "David", "LastName" : "Miller", "Age" : 23 }
{ "_id" : ObjectId("5e4d45385d93261e4bc9ea34"), "FirstName" : "John", "LastName" : "Smith", "Age" : 24 }
{ "_id" : ObjectId("5e4d46cf5d93261e4bc9ea35"), "FirstName" : "Adam", "LastName" : "Doe", "Age" : 21 }

以下是对 AND 和 OR 进行组合的查询 −

> db.demo293.find( {
...   $and : [
...      {
...         $or : [
...            {"FirstName" : "John"},
...            {"LastName" : "Brown"}
...         ]
...      },
...      {
...         Age:24
...      }
...   ]
...} )

这将产生以下输出 −

{ "_id" : ObjectId("5e4d45075d93261e4bc9ea32"), "FirstName" : "Chris", "LastName" : "Brown", "Age" : 24 }
{ "_id" : ObjectId("5e4d45385d93261e4bc9ea34"), "FirstName" : "John", "LastName" : "Smith", "Age" : 24 }

更新于:31-Mar-2020

564 次浏览

开启您的职业生涯

完成该课程以获得认证

开始
广告