如何创建“;触发器”;在MongoDB中

本文关键字:触发器 MongoDB 何创建 创建 | 更新日期: 2023-09-27 18:20:42

我想创建一个触发器,其中插入的每个子文档将在其他集合中增加一个字段,用于生成该集合的子文档数。

我尝试使用MapReduce创建一个搜索,但对于注册表的Milions来说速度非常慢。

注意:我使用C#,但如果你喜欢在Bson中演示如何操作,没问题

整理我的收藏

public class Header
{
    public Header()
    {
        Operation= new List<Operation>();
    }
    public ObjectId Id { get; set; }
    public Int64 Code1 {get; set;}
    public Int64 Code2 {get; set;}
    public string Name { get; set; }
    public List<Operation> Operations { get; set; }
}
public class Operation
{
    public Operation()
    {
        Itens = new List<Item>();
    }
    public string Value { get; set; }
    public List<Item> Item { get; set; }
}
public class Item
{
    public string Value { get; set; }
}

如何创建“;触发器”;在MongoDB中

MongoDB没有触发器。您必须在应用程序中通过插入文档来实现这一点,当插入成功时,您可以使用$add运算符来增加其他文档中的字段。

更新:如果你碰巧从服务提供商那里租了一个MongoDB Atlas实例,那么你可以使用触发器。但是,如果你想在自己的服务器上运行MongoDB,那么这个功能是不可用的。

MongoDB自2019年7月起,于2020年推出了触发器。https://docs.mongodb.com/stitch/triggers/database-triggers/

您可以使用更改流,特别是驱动程序中可用的collection.watch方法。

MongoB Atlas中的数据库触发器在后台使用这些触发器。

使用MongoDB Atlas触发器的脚本示例:

exports = function(changeEvent) {
  const { updateDescription, fullDocument, ns } = changeEvent;
  const updatedFields = Object.keys(updateDescription.updatedFields);
  
  // For debug
  //console.log('changeEvent', JSON.stringify(changeEvent));
  const isUpdated = updatedFields.some(field =>
    field.match(/updatedAt/)
  );
  const updatedAt = fullDocument.updatedAt;
  // Prevent update again after the update
  if (!isUpdated || !updatedAt) {
    const { _id } = fullDocument;
    
    console.log(`Triggered! ${ns.db}:${ns.coll}:${_id}, isUpdated:${isUpdated ? 'true' : 'false'}, updatedAt:${updatedAt}`);
    
    const mongodb = context.services.get(ns.db /* Cluster Name, like the DB name */);
    const collection = mongodb.db(ns.db).collection(ns.coll);
    
    collection.updateOne({
      _id: _id,
    }, {
      $set: {
        updatedAt: new Date(),
      }
    });
  }
};

来源:https://stackoverflow.com/a/73310825/717267