使用MongoDB OR运算符选择多个值
首先让我们创建一个包含文档的集合-
> db.demo270.insertOne({"ClientName":"Chirs","Age":34}); { "acknowledged" : true, "insertedId" : ObjectId("5e481e371627c0c63e7dbab8") } > db.demo270.insertOne({"ClientName":"David","Age":31}); { "acknowledged" : true, "insertedId" : ObjectId("5e481e3d1627c0c63e7dbab9") } > db.demo270.insertOne({"ClientName":"Bob","Age":31}); { "acknowledged" : true, "insertedId" : ObjectId("5e481e431627c0c63e7dbaba") } > db.demo270.insertOne({"ClientName":"Carol","Age":36}); { "acknowledged" : true, "insertedId" : ObjectId("5e481e491627c0c63e7dbabb") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo270.find();
这将产生以下输出-
{ "_id" : ObjectId("5e481e371627c0c63e7dbab8"), "ClientName" : "Chirs", "Age" : 34 } { "_id" : ObjectId("5e481e3d1627c0c63e7dbab9"), "ClientName" : "David", "Age" : 31 } { "_id" : ObjectId("5e481e431627c0c63e7dbaba"), "ClientName" : "Bob", "Age" : 31 } { "_id" : ObjectId("5e481e491627c0c63e7dbabb"), "ClientName" : "Carol", "Age" : 36 }
以下是使用OR运算符选择多个值的查询-
> db.demo270.find({ ... "$or" : [ ... { ... "ClientName" : "Carol" ... }, ... { ... "Age" : 31 ... } ... ] ...} ...);
这将产生以下输出-
{ "_id" : ObjectId("5e481e3d1627c0c63e7dbab9"), "ClientName" : "David", "Age" : 31 } { "_id" : ObjectId("5e481e431627c0c63e7dbaba"), "ClientName" : "Bob", "Age" : 31 } { "_id" : ObjectId("5e481e491627c0c63e7dbabb"), "ClientName" : "Carol", "Age" : 36 }