當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


MongoDB $and用法及代碼示例

簡介

MongoDB 提供了多種邏輯查詢操作符。 $and 運算符是這些運算符之一。 $and 運算符用於對一個或多個表達式的數組執行邏輯與運算。用戶可以根據需要在 find()、update() 等方法中使用該運算符。

用戶還可以在逗號 (,) 的幫助下使用 "AND operation"。 $and 運算符使用短路評估。當用戶在多個表達式中指定相同的字段或運算符時,用戶可以使用“$AND 運算”。

例如,假設有兩個表達式(e1 和 e2)。如果第一個表達式 (e1) 的計算結果為假,則不會計算第二個表達式 (e2)。

用法:

{ $and:[ { Expression 1 }, { Expression 2 }, { Expression 3 }, ..., { Expression N } ] }
or
{ { Expression 1 }, { Expression 2 }, { Expression 3 },..., { Expression N }}

例子:

在以下示例中,我們正在使用:

Database:JavaTpoint
Collection:Student
Document:Six documents that contain the details of the students
[
        {
                "std_name":"Jack",
                "sex":"Male",
                "class":"VI",
                "age":11,
                "grd_point":33
        },
        {
                "std_name":"Jenny",
                "sex":"Female",
                "class":"VI",
                "age":13,
                "grd_point":30
        },
        {
                "std_name":"Thomas",
                "sex":"Male",
                "class":"V",
                "age":11,
                "grd_point":35.1257
        },
        {
                "std_name":"Lassy",
                "sex":"Female",
                "class":"X",
                "age":17,
                "grd_point":36.2514
        },
        {
                "std_name":"Mia",
                "sex":"Female",
                "class":"X",
                "age":19,
                "grd_point":35.5201
        }
       {
                "std_name":"Mike,
                "sex":"Male",
                "class":"V",
                "age":16,
                "grd_point":35.5201
        }
]

使用 $and 運算符匹配兩個條件值:

在此示例中,我們僅從滿足以下條件的學生那裏獲取文檔:

  1. 學生的 "Class" 是 VI。
  2. 學生的 "Sex" 是女性。
>db.student.find({$and:[{"sex":"Female"}, {"class":"VI"}]}).pretty();

SQL等效命令:

SELECT * 
FROM student 
WHERE sex = "Female" AND class = "VI";

輸出:

MongoDB $and Operator

注意:find() 方法以非結構化格式顯示文檔,因此它使用 pretty() 方法以格式化方式顯示結果。

使用 $and 運算符匹配多個條件值

在此示例中,我們僅從滿足以下條件的學生那裏獲取文檔:

  1. 學生的 "Age" 是 17。
  2. 學生的 "Sex" 是女性。
  3. 學生的 "Class" 是 X。
>db.student.find({$and:[{"sex":"Female"}, {"grd_point":{ $gte:31 }}, {"class":"X"}]}).pretty();

SQL等效命令:

SELECT * 
FROM student 
WHERE sex = "Female" AND grd_point >= 31 AND class = "X";

輸出:

MongoDB $and Operator



相關用法


注:本文由純淨天空篩選整理自 MongoDB $and Operator。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。