简体   繁体   English

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

[英]How to create "trigger" in MongoDB

I would like of create a trigger where, to each subdocument inserted would increment in other collection a field, for generate a count of subdocuments that collection.我想创建一个触发器,其中插入的每个子文档都会在其他集合中增加一个字段,以生成该集合的子文档计数。

I tried create a search using MapReduce, but for Milions of the Registries is very slow.我尝试使用 MapReduce 创建搜索,但是对于 Milions of the Registries 来说非常慢。

Note: I use C#, but if you like show how to do in Bson, no problem.注意:我使用 C#,但如果你喜欢在 Bson 中展示如何做,没问题。

Extructure my collection展开我的收藏

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 has no triggers. MongoDB 没有触发器。 You will have to implement this in your application by inserting the document and when the insert was successful, you use the $add operator to increment the field in the other document.您必须通过插入文档在您的应用程序中实现这一点,当插入成功时,您可以使用$add 运算符来增加另一个文档中的字段。

Update: If you happen to rent a MongoDB Atlas instance from a service provider, then you can use triggers .更新:如果您碰巧从服务提供商那里租用了MongoDB Atlas实例,那么您可以使用 triggers But if you want to run MongoDB on your own servers, then this feature is not available.但是如果你想在自己的服务器上运行MongoDB,那么这个功能是不可用的。

MongoDB does in 2020 since July 2019, have triggers.自 2019 年 7 月以来,MongoDB 在 2020 年确实有触发器。 https://docs.mongodb.com/stitch/triggers/database-triggers/ https://docs.mongodb.com/stitch/triggers/database-triggers/

You can use change streams , specifically the collection.watch method available in drivers.您可以使用更改流,特别是驱动程序中可用的collection.watch方法。

Database triggers from MongoB Atlas use these under the hood.来自 MongoB Atlas 的数据库触发器在幕后使用这些。

Script example using MongoDB Atlas Triggers :使用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(),
      }
    });
  }
};

Source: https://stackoverflow.com/a/73310825/717267资料来源: https://stackoverflow.com/a/73310825/717267

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM