MongoDB 如何使用 $exists 和 $cond 来查询和条件判断

在本文中,我们将介绍在 MongoDB 中如何使用 $exists$cond 来查询和条件判断。

MongoDB $exists 运算符

$existsMongoDB 中的一个查询运算符,用于检查文档中是否存在某个字段或属性。其语法为:

{ field: { $exists: <boolean> } }
Bash
  • <boolean>:表示布尔值,可选。若为 true ,表示查询只返回包含该字段的文档;若为 false ,表示查询只返回不包含该字段的文档。

下面是一个使用 $exists 运算符的示例:

> db.users.insertMany([
    { name: "Alice", age: 20 },
    { name: "Bob", age: 25 },
    { name: "Charlie" }
])

> db.users.find({ age: { $exists: true } })
{ "_id" : ObjectId("5fbdb70086f20ca1f2a68d8c"), "name" : "Alice", "age" : 20 }
{ "_id" : ObjectId("5fbdb70086f20ca1f2a68d8d"), "name" : "Bob", "age" : 25 }
Bash

在上面的示例中,我们插入了三个用户文档,其中 AliceBobage 字段,而 Charlie 没有。我们使用 $exists 查询只返回了包含 age 字段的文档。

MongoDB $cond 条件表达式

$cond 是 MongoDB 中的一个条件表达式操作符,用于根据条件返回匹配的字段值。其语法为:

{
  $cond: {
    if: <condition>,
    then: <expression>,
    else: <expression>
  }
}
Bash
  • <condition>:表示条件,可选。当条件满足时,返回 true ;否则,返回 false
  • <expression>:表示条件满足时要返回的值或表达式。

下面是一个使用 $cond 运算符的示例:

> db.sales.insertMany([
    { product: "A", total: 100, discount: 10 },
    { product: "B", total: 200, discount: 20 },
    { product: "C", total: 300 }
])

> db.sales.aggregate([
    {
      project: {
        product: 1,
        discountPrice: {cond: {
            if: { exists: "discount" },
            then: { multiply: [ "total", { divide: [ "discount", 100 ] } ] },
            else: 0
          }
        }
      }
    }
])
Bash

在上面的示例中,我们插入了三个销售记录文档,其中 ABdiscount 字段,而 C 没有。我们使用 $cond 条件表达式计算了折扣后的价格,并将其存储在 discountPrice 字段中。

总结

本文介绍了在 MongoDB 中使用 $exists 运算符来检查文档中是否存在某个字段或属性,并使用 $cond 条件表达式根据条件返回匹配的字段值。通过掌握这些运算符,您可以更加灵活和高效地进行 MongoDB 数据的查询和条件判断。希望本文能对您在 MongoDB 开发中有所帮助!

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程