首先让我们创建一个包含文档的集合-
> 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 }