How to create "trigger" in MongoDB
Solution 1
MongoDB has no triggers. 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.
Update: If you happen to rent a MongoDB Atlas instance from a service provider, then you can use triggers. But if you want to run MongoDB on your own servers, then this feature is not available.
Solution 2
MongoDB does in 2020 since July 2019, have triggers. https://docs.mongodb.com/stitch/triggers/database-triggers/
Solution 3
You can use change streams, specifically the collection.watch method available in drivers.
Database triggers from MongoB Atlas use these under the hood.
Renatto Machado
Updated on June 12, 2022Comments
-
Renatto Machado almost 2 years
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.
Note: I use C#, but if you like show how to do in Bson, no problem.
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; } }
-
Renatto Machado over 9 yearsI know that MongoDB not has trigger. But, I can not use function for this?
-
Renatto Machado over 9 yearsNo see how $add oprator can help me. I Ready documentation, but no see how resolve my question.
-
Renatto Machado over 9 yearsNot was used $add operator, but use the ideia for design solution where i created a collection count for each document of the my collection.
-
Heiko Scholze over 3 yearsDatabase Triggers are only available for MongoDB Atlas clusters that are running MongoDB version 3.6 or newer!