MongoDB(40)如何使用$match阶段?

在MongoDB中,使用聚合管道进行过滤操作的关键阶段是 $match。该阶段允许你根据指定的条件筛选文档,类似于SQL中的 WHERE 子句。

使用 $match 阶段的基本结构

$match 阶段的结构如下:

javascript 复制代码
{ 
  $match: { 
    <field1>: <condition1>, 
    <field2>: <condition2>, 
    // 其他条件
  } 
}

代码示例

以下是使用Node.js进行过滤操作的详细示例。首先确保安装了MongoDB的Node.js驱动:

bash 复制代码
npm install mongodb

插入示例数据

javascript 复制代码
const { MongoClient } = require('mongodb');

async function insertData() {
    const uri = "mongodb://localhost:27017";
    const client = new MongoClient(uri, { useUnifiedTopology: true });

    try {
        await client.connect();
        const db = client.db('myDatabase');
        const collection = db.collection('orders');

        await collection.deleteMany({}); // 清空集合

        await collection.insertMany([
            { customerId: 1, amount: 100, status: "shipped" },
            { customerId: 1, amount: 200, status: "pending" },
            { customerId: 2, amount: 150, status: "shipped" },
            { customerId: 2, amount: 50, status: "pending" },
            { customerId: 3, amount: 250, status: "shipped" }
        ]);

        console.log("Data inserted");
    } finally {
        await client.close();
    }
}

insertData().catch(console.error);

使用 $match 进行过滤

javascript 复制代码
async function aggregateData() {
    const uri = "mongodb://localhost:27017";
    const client = new MongoClient(uri, { useUnifiedTopology: true });

    try {
        await client.connect();
        const db = client.db('myDatabase');
        const collection = db.collection('orders');

        // 使用 $match 进行过滤,筛选出 amount 大于 100 的订单
        console.log("\n$match stage (amount > 100):");
        let result = await collection.aggregate([
            { $match: { amount: { $gt: 100 } } } // 过滤出 amount 大于 100 的订单
        ]).toArray();
        console.log(result);

        // 使用 $match 进行过滤,筛选出状态为 shipped 且 amount 小于 200 的订单
        console.log("\n$match stage (status = shipped and amount < 200):");
        result = await collection.aggregate([
            { $match: { status: "shipped", amount: { $lt: 200 } } } // 过滤出 status 为 shipped 且 amount 小于 200 的订单
        ]).toArray();
        console.log(result);

        // 使用 $match 进行过滤,筛选出 customerId 为 2 或 amount 在 100 到 200 之间的订单
        console.log("\n$match stage (customerId = 2 or amount between 100 and 200):");
        result = await collection.aggregate([
            { $match: { $or: [ { customerId: 2 }, { amount: { $gte: 100, $lte: 200 } } ] } } // 过滤出 customerId 为 2 或 amount 在 100 到 200 之间的订单
        ]).toArray();
        console.log(result);

    } finally {
        await client.close();
    }
}

aggregateData().catch(console.error);

在这个示例中,我们演示了如何使用 $match 阶段进行过滤操作:

  1. 筛选出 amount 大于 100 的订单
  2. 筛选出 statusshippedamount 小于 200 的订单
  3. 筛选出 customerId 为 2 或 amount 在 100 到 200 之间的订单

运行这个脚本后,你会得到如下结果(示例输出):

javascript 复制代码
// amount > 100 结果
$match stage (amount > 100):
[
  { customerId: 1, amount: 200, status: 'pending' },
  { customerId: 2, amount: 150, status: 'shipped' },
  { customerId: 3, amount: 250, status: 'shipped' }
]

// status = shipped and amount < 200 结果
$match stage (status = shipped and amount < 200):
[
  { customerId: 1, amount: 100, status: 'shipped' },
  { customerId: 2, amount: 150, status: 'shipped' }
]

// customerId = 2 or amount between 100 and 200 结果
$match stage (customerId = 2 or amount between 100 and 200):
[
  { customerId: 1, amount: 100, status: 'shipped' },
  { customerId: 1, amount: 200, status: 'pending' },
  { customerId: 2, amount: 150, status: 'shipped' },
  { customerId: 2, amount: 50, status: 'pending' }
]

其他语言示例

类似的过滤操作也可以在其他编程语言中实现,如Python。以下是Python的示例代码:

安装PyMongo

在终端中运行以下命令来安装PyMongo:

bash 复制代码
pip install pymongo

使用Python进行过滤

python 复制代码
from pymongo import MongoClient

def main():
    client = MongoClient('mongodb://localhost:27017/')
    db = client['myDatabase']
    collection = db['orders']

    # 使用 $match 进行过滤,筛选出 amount 大于 100 的订单
    print("\n$match stage (amount > 100):")
    pipeline = [
        { '$match': { 'amount': { '$gt': 100 } } } # 过滤出 amount 大于 100 的订单
    ]
    result = list(collection.aggregate(pipeline))
    for doc in result:
        print(doc)

    # 使用 $match 进行过滤,筛选出 status 为 shipped 且 amount 小于 200 的订单
    print("\n$match stage (status = shipped and amount < 200):")
    pipeline = [
        { '$match': { 'status': "shipped", 'amount': { '$lt': 200 } } } # 过滤出 status 为 shipped 且 amount 小于 200 的订单
    ]
    result = list(collection.aggregate(pipeline))
    for doc in result:
        print(doc)

    # 使用 $match 进行过滤,筛选出 customerId 为 2 或 amount 在 100 到 200 之间的订单
    print("\n$match stage (customerId = 2 or amount between 100 and 200):")
    pipeline = [
        { '$match': { '$or': [ { 'customerId': 2 }, { 'amount': { '$gte': 100, '$lte': 200 } } ] } } # 过滤出 customerId 为 2 或 amount 在 100 到 200 之间的订单
    ]
    result = list(collection.aggregate(pipeline))
    for doc in result:
        print(doc)

if __name__ == '__main__':
    main()

运行这个脚本后,你会得到类似的结果。通过这些示例,你可以了解到如何在不同编程语言中使用MongoDB的聚合管道进行过滤操作,并根据各种条件筛选文档。

$match 示例进一步深入:

1. 基本字段匹配

javascript 复制代码
{ $match: { status: "shipped" } }

这个 $match 将筛选出所有 status 字段等于 "shipped" 的文档。

2. 使用比较运算符

javascript 复制代码
{ $match: { amount: { $gt: 100 } } }

这个 $match 将筛选出所有 amount 字段大于 100 的文档。常用的比较运算符包括:

  • $gt:大于
  • $gte:大于或等于
  • $lt:小于
  • $lte:小于或等于
  • $eq:等于
  • $ne:不等于

3. 逻辑运算符

javascript 复制代码
{ $match: { $or: [ { customerId: 2 }, { amount: { $gte: 100, $lte: 200 } } ] } }

这个 $match 将筛选出所有 customerId 为 2 或 amount 在 100 到 200 之间的文档。常用的逻辑运算符包括:

  • $and:与
  • $or:或
  • $not:非
  • $nor:都不

4. 字符串模式匹配

javascript 复制代码
{ $match: { status: { $regex: "^ship", $options: "i" } } }

这个 $match 将筛选出所有 status 字段以 "ship" 开头的文档,且匹配时不区分大小写。

相关推荐
不会写DN2 小时前
Go中的泛型与any、interface有什么区别?
开发语言·后端·golang
无心水2 小时前
【java开发常见错误】5、HTTP调用避坑指南:超时、重试、并发,一个都不能少
java·开发语言·后端·http·架构师·http调用·后端开发错误
iPadiPhone2 小时前
Java 泛型与通配符全链路解析及面试进阶
java·开发语言·后端·面试
无心水2 小时前
【文档解析】4、跨平台文档解析:JS/Go/C#全攻略
javascript·后端·golang·c#·架构师·大数据分析·分布式系统利器
清汤饺子2 小时前
用了大半年 Claude Code,我总结了 16 个实用技巧
前端·javascript·后端
ん贤5 小时前
Go channel 深入解析
开发语言·后端·golang
changhong19868 小时前
如何在 Spring Boot 中配置数据库?
数据库·spring boot·后端
月月玩代码10 小时前
Actuator,Spring Boot应用监控与管理端点!
java·spring boot·后端
XPoet11 小时前
AI 编程工程化:Skill——给你的 AI 员工装上技能包
前端·后端·ai编程