使用“或”條件的 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")
}

更新於:2019 年 7 月 30 日

413 次瀏覽

開啟你的 職業生涯

透過完成課程,獲得認證

立即開始
廣告
© . All rights reserved.