在 MongoDB 中查詢非空值
- MongoDB 中的
$ne運算子 - MongoDB 中的
$eq運算子 - 在 MongoDB 中查詢
is Not Null值 -
$ne運算子查詢 MongoDB 中字串欄位上的is Not Null值 - 在 MongoDB 中
$ne運算子的數值欄位上查詢is Not Null - 在 MongoDB 中
$ne運算子查詢非空值 - 在 MongoDB 中
$eq運算子指定非 Null 值
這篇 MongoDB 文章將解釋如何在 MongoDB 中查詢非空值。要查詢非空值,你可以使用 $ne 運算子和 $eq 運算子,然後指定要查詢的所需值。
本文向讀者展示瞭如何使用各種方法和示例在 MongoDB 中查詢非空值。所以,讓我們開始這個指南。
MongoDB 中的 $ne 運算子
該運算子的語法是:
{ field: { $ne: value } } $ne 運算子選擇 field 的值與給定 value 不同的所有文件。它包括不包含 field 的文件。
MongoDB 中的 $eq 運算子
此運算子指定相等條件。例如,$eq 運算子匹配 field 的值等於指定 value 的文件。
此運算子的語法是:
{ <field>: { $eq: <value> } } 指定 $eq 運算子等效於使用形式 { field: <value> },除非 <value> 是正規表示式。
在 MongoDB 中查詢 is Not Null 值
現在讓我們通過檢視如何實現這一目標的示例來幫助你開始。
下面是你將用來說明一些操作的集合。
db={ "teams": [ { team: "Manchester City", position: "1st", points: 70 }, { team: "Liverpool", position: null, points: 69 }, { team: "Chelsea", position: "3rd", points: 59 }, { team: "Arsenal", position: "4th", points: null }, { team: "Tottenham", position: "5th", points: 51 }, { team: "Manchester United", position: "6th", points: 50 }, ] } $ne 運算子查詢 MongoDB 中字串欄位上的 is Not Null 值
你將使用 $ne 運算子將表示式傳遞給 $ne 運算子,該運算子否定特定欄位的空值,以查詢在本示例中不為空的字串欄位。對於此示例,你可以使用下面的查詢。
db.teams.find({ points: { $ne: null } }) 執行上述查詢時返回的結果可以在下面的螢幕截圖中看到。

你發現所有沒有 points 欄位值指定為空的此類文件。
在 MongoDB 中 $ne 運算子的數值欄位上查詢 is Not Null
在這種情況下,你將選擇那些沒有數值欄位值為空的文件。對於此示例,你可以使用下面的查詢。
db.teams.find({ position: { $ne: null } }) 執行上述查詢時返回的結果可以在下面的螢幕截圖中看到。

你可以再次在 position 欄位中找到沒有 null 作為值的文件。
在 MongoDB 中 $ne 運算子查詢非空值
在此示例中,你將使用帶有空白字串的 $ne 運算子來查詢 MongoDB 中的非空值。
由於你在上面使用的集合沒有任何此類具有空白字串值的文件,你可以在集合中新增一些。以下文件將新增到集合中,如下所示。
db={ "teams": [ { team: "Manchester City", position: "1st", points: 70 }, { team: "Liverpool", position: null, points: 69 }, { team: "Chelsea", position: "3rd", points: 59 }, { team: "Arsenal", position: "4th", points: null }, { team: "Tottenham", position: "5th", points: 51 }, { team: "Manchester United", position: "6th", points: 50 }, { team: "West Ham", position: "", points: 48 }, { team: "Wolves", position: "", points: 46 } ] } 好的,現在你的收藏中又新增了兩個文件,你可以開始了。現在你可以使用 $ne 運算子通過指定一個空白字串來查詢非空值。
對於此示例,你可以使用下面的查詢。
db.teams.find({ position: { $ne: "" } }) 執行上述程式碼時返回的結果可以在下面的螢幕截圖中看到。

這次你無法找到新新增的文件。
在 MongoDB 中 $eq 運算子指定非 Null 值
在此示例中,你將使用 $eq 運算子來查詢非空值,因為你將傳遞一個要查詢的值,以用外行的術語查詢該不是空值。
讓我們尋找排名第三的球隊。對於此示例,你可以使用下面的查詢。
db.teams.find({ position: { $eq: "3rd" } }) 執行上述程式碼時返回的結果可以在下面的螢幕截圖中看到。

你在集合中找到了當前排名第三的團隊。
因此,通過這篇 MongoDB 文章的幫助,你學習瞭如何使用 $ne 和 $eq 運算子查詢非空值。