要了解带有或条件的查询,让我们用文档创建一个集合。使用文档创建集合的查询如下-
> db.orConditionDemo.insertOne({"CustomerName":"Larry","ShippingDate":new ISODate("2018-01-29")}); { "acknowledged" : true, "insertedId" : ObjectId("5c8ec5262f684a30fbdfd56a") } > db.orConditionDemo.insertOne({"CustomerName":"Mike","ShippingDate":new ISODate("2019-04-13")}); { "acknowledged" : true, "insertedId" : ObjectId("5c8ec5362f684a30fbdfd56b") } > db.orConditionDemo.insertOne({"CustomerName":"Bob","ShippingDate":new ISODate("2019-02-21")}); { "acknowledged" : true, "insertedId" : ObjectId("5c8ec5422f684a30fbdfd56c") } > db.orConditionDemo.insertOne({"CustomerName":"David","ShippingDate":new ISODate("2019-03-15")}); { "acknowledged" : true, "insertedId" : ObjectId("5c8ec5532f684a30fbdfd56d") } > db.orConditionDemo.insertOne({"CustomerName":"John","ShippingDate":new ISODate("2019-03-19")}); { "acknowledged" : true, "insertedId" : ObjectId("5c8ec56c2f684a30fbdfd56e") }
在find()
method的帮助下显示集合中的所有文档。查询如下-
> db.orConditionDemo.find().pretty();
以下是输出-
{ "_id" : ObjectId("5c8ec5262f684a30fbdfd56a"), "CustomerName" : "Larry", "ShippingDate" : ISODate("2018-01-29T00:00:00Z") } { "_id" : ObjectId("5c8ec5362f684a30fbdfd56b"), "CustomerName" : "Mike", "ShippingDate" : ISODate("2019-04-13T00:00:00Z") } { "_id" : ObjectId("5c8ec5422f684a30fbdfd56c"), "CustomerName" : "Bob", "ShippingDate" : ISODate("2019-02-21T00:00:00Z") } { "_id" : ObjectId("5c8ec5532f684a30fbdfd56d"), "CustomerName" : "David", "ShippingDate" : ISODate("2019-03-15T00:00:00Z") } { "_id" : ObjectId("5c8ec56c2f684a30fbdfd56e"), "CustomerName" : "John", "ShippingDate" : ISODate("2019-03-19T00:00:00Z") }
这是具有多个或条件的查询-
> db.orConditionDemo.find({$or: [{ShippingDate: {$gte: new ISODate()}}, {ShippingDate: null}]}).pretty();
以下是输出-
{ "_id" : ObjectId("5c8ec5362f684a30fbdfd56b"), "CustomerName" : "Mike", "ShippingDate" : ISODate("2019-04-13T00:00:00Z") } { "_id" : ObjectId("5c8ec56c2f684a30fbdfd56e"), "CustomerName" : "John", "ShippingDate" : ISODate("2019-03-19T00:00:00Z") }