如何在 MongoDB 中實現 $or 運算子


使用 MongoDB 中的 $or 運算子求值一個或多個表示式。以下是語法 −

db.yourCollectionName.find({ $or: [{ "yourFieldName": yourValue1 }, { "yourFieldName": yourValue2} ] } ).pretty();

讓我們首先使用文件建立一個集合 −

> db.orOperatorDemo.insertOne({"StudentNames":["John","Carol","Sam"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd6b80a6d78f205348bc61b")
}
> db.orOperatorDemo.insertOne({"StudentNames":["Robert","Chris","David"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd6b8266d78f205348bc61c")
}
> db.orOperatorDemo.insertOne({"StudentNames":["John"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd6b8346d78f205348bc61d")
}

以下是使用 find() 方法在集合中顯示所有文件的查詢 −

> db.orOperatorDemo.find().pretty();

這將產生以下輸出 −

{
   "_id" : ObjectId("5cd6b80a6d78f205348bc61b"),
   "StudentNames" : [
      "John",
      "Carol",
      "Sam"
   ]
}
{
   "_id" : ObjectId("5cd6b8266d78f205348bc61c"),
   "StudentNames" : [
      "Robert",
      "Chris",
      "David"
   ]
}
{
   "_id" : ObjectId("5cd6b8346d78f205348bc61d"),
   "StudentNames" : [
      "John"
   ]
}

以下是 $or 運算子語法查詢 −

> db.orOperatorDemo.find({ $or: [{ "StudentNames": "Carol" }, { "StudentNames": "John"} ] } ).pretty();

這將產生以下輸出 −

{
   "_id" : ObjectId("5cd6b80a6d78f205348bc61b"),
   "StudentNames" : [
      "John",
      "Carol",
      "Sam"
   ]
}
{
   "_id" : ObjectId("5cd6b8346d78f205348bc61d"),
   "StudentNames" : [
      "John"
   ]
}

更新於: 2019 年 30 日 7 月

129 次觀看

啟動你的職業

完成課程以獲得認證

開始
廣告
© . All rights reserved.