You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB触发器未执行预期更新,匹配数为0问题求助

MongoDB触发器匹配文档数为0的排查与修复

问题现象

创建触发器实现以下逻辑:获取服务器时间,对比文档的DueDate字段,当DueDate≤服务器时间且Borrowed为true时,将Borrowed设为false。但触发器执行后,matchedCount和modifiedCount均为0,无预期修改效果。

原触发器代码

exports = function(changeEvent) {
    const mongo = context.services.get("MongoDB");
    const now = new Date();
    const booksLended = mongo.db("test").collection("bookslendeds");
    var filter = {DueDate: {$lt: now.toISOString()}, Borrowed: true};
    var update = {$set: {Borrowed: false}};
    console.log(JSON.stringify(filter));
    console.log(JSON.stringify(update));

    return booksLended.updateMany(filter, update);
};

执行日志

> ran on Wed Jan 18 2023 23:48:10 GMT+0100 (Central European Standard Time)
> took 524.689137ms
> logs: 
{"DueDate":{"$lt":"2023-01-18T22:48:11.778Z"},"Borrowed":true}
{"$set":{"Borrowed":false}}
> result: 
{
  "matchedCount": {
    "$numberInt": "0"
  },
  "modifiedCount": {
    "$numberInt": "0"
  }
}
> result (JavaScript): 
EJSON.parse('{"matchedCount":{"$numberInt":"0"},"modifiedCount":{"$numberInt":"0"}}')

数据模型说明

bookslendeds集合中,DueDate字段类型为Date,Borrowed字段类型为Boolean。

问题原因

代码中使用now.toISOString()将Date对象转为了字符串类型,而数据库里的DueDate是Date类型。MongoDB不会自动转换类型进行匹配,字符串与Date类型的对比无法命中任何文档,导致匹配数为0。

修复后的代码

exports = function(changeEvent) {
    const mongo = context.services.get("MongoDB");
    const now = new Date();
    const booksLended = mongo.db("test").collection("bookslendeds");
    // 直接使用Date对象,而非转成字符串
    var filter = {DueDate: {$lt: now}, Borrowed: true};
    var update = {$set: {Borrowed: false}};
    console.log(JSON.stringify(filter));
    console.log(JSON.stringify(update));

    return booksLended.updateMany(filter, update);
};

额外优化

如果需要匹配DueDate≤服务器时间的文档,应将$lt改为$lte,确保等于当前时间的文档也能被匹配到:

var filter = {DueDate: {$lte: now}, Borrowed: true};

内容的提问来源于stack exchange,提问作者Rabeles

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 14:50:15