【问题标题】:Mongo changeStream for a find query用于查找查询的 Mongodb changeStream
【发布时间】:2020-09-15 23:52:18
【问题描述】:

我想对 mongo 集合进行查询,当集合更改时,我想再次运行查询。但是为了优化它,我不想在每次集合更改时运行查询,只有在匹配查询的文档发生更改时才运行查询。我有以下代码:

const query = { author: someUserID };
const fetch = async () => await collection.find(query).toArray();
const watcher = collection
        .watch([{ $match: { fullDocument: query } }])
        .on("change", () => fetch().then(sendData)); // This does not work
fetch().then(sendData); // This works

在第一次运行时,它会获取文档并执行sendData,但是当插入新文档时,不会触发该事件。当我在没有参数的情况下赢得collection.watch() 时,它会起作用。

问题出在哪里? 谢谢。

编辑:我希望能够将query 重用于.find().watch()

【问题讨论】:

    标签: node.js mongodb changestream


    【解决方案1】:

    该示例中的$match 阶段本质上是

    {$match: { fullDocument: { author: someUserId }}}
    

    只有当fullDocument 正好是{ author: someUserId } 且没有其他字段或值时,才会匹配

    为了在允许文档中其他字段的同时匹配作者,请使用点分符号,例如

    const query = { "fullDocument.author": someUserId };
    

    并匹配如下:

    {$match: query }
    

    【讨论】:

    • 这样我将无法重用.find().watch() 的查询。我会更新问题。
    猜你喜欢
    • 2018-09-05
    • 2015-06-24
    • 2021-07-19
    • 2016-08-13
    • 1970-01-01
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多