Reputation: 1574
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.
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; }
}
Upvotes: 12
Views: 27442
Reputation: 18937
Script example using MongoDB Atlas Triggers:
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
Upvotes: 0
Reputation: 629
You can use change streams, specifically the collection.watch method available in drivers.
Database triggers from MongoB Atlas use these under the hood.
Upvotes: 3
Reputation: 69663
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.
Upvotes: 15
Reputation: 365
MongoDB does in 2020 since July 2019, have triggers. https://docs.mongodb.com/stitch/triggers/database-triggers/
Upvotes: 9