【问题标题】:Aggregate Pipeline to exclude collections from db.watch() MongoDB聚合管道以从 db.watch() MongoDB 中排除集合
【发布时间】:2023-01-10 02:00:05
【问题描述】:

我正在使用 MongoDB change Streams 来监视我的数据库中的更改。除了两个之外,我想观察每个系列的变化。是这样的:

const pipeline = [{ $match: { name: { $ne: "excludedCollection1" } } }, 
    { $match: { name: { $ne: "excludedCollection2" } } }];
const db = client.db("myDatabase");
const changeStream = db.watch(pipeline);

但是,这段代码并不排除这两个集合。

【问题讨论】:

    标签: mongodb aggregate pipeline changestream


    【解决方案1】:

    您不能通过管道本身的集合名称过滤掉集合。根据 mongo manualpipeline 用于“指定管道以过滤/修改更改事件输出”。如果您在 change events 中注意到,有一个 ns 属性提供更改的命名空间。您可以使用您的管道排除此 ns 属性的匹配项:

      const pipeline = [
      {
        $match: {
          $and: [
            {
              ns: {
                $ne: {
                  db: "myDatabase",
                  coll: "notifications",
                },
              },
            },
            {
              ns: {
                $ne: {
                  db: "myDatabase",
                  coll: "rules",
                },
              },
            },
          ],
        },
      },
    ];
    const db = client.db("myDatabase");
    const changeStream = db.watch(pipeline);
    

    【讨论】:

      猜你喜欢
      • 2020-01-12
      • 1970-01-01
      • 2022-09-23
      • 1970-01-01
      • 1970-01-01
      • 2015-04-24
      • 2020-09-20
      • 2021-04-05
      • 1970-01-01
      相关资源
      最近更新 更多