使用“或”条件的 MongoDB 查询?
要理解带“或”条件的查询,我们使用文档创建一个集合。使用文档创建集合的查询如下所示:
> 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() 方法显示集合中的所有文档。查询如下:
> 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")
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP