Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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; }
}
like image 352
Renatto Machado Avatar asked Sep 05 '14 13:09

Renatto Machado


People also ask

What is MongoDB stitch?

The MongoDB Stitch serverless platform accelerates application development with simple, secure access to data and services from the client – getting your apps to market faster while reducing operational costs and effort. The Stitch serverless platform provides three services: Stitch QueryAnywhere.

How do I listen for changes in MongoDB collection?

The only reliable, performant way to do this is to create a tailable cursor on local db: oplog.rs collection to get ALL changes to MongoDB and do with it what you will.

Can we create stored procedure in MongoDB?

First and foremost, MongoDB does not support Stored Procedures, but it does provide a stored javascript feature. This feature offers similar functions and allows writing code in Javascript. It might seem strange but in a real language, it is better to program.

Is MongoDB realm free?

All Atlas App Services apps in a MongoDB Atlas project share a single monthly free tier. All usage below the free tier thresholds in a given month is not billed. Once the sum of all application usage in a project exceeds a free tier usage threshold, App Services immediately begins to bill for any additional usage.


1 Answers

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.

like image 172
Philipp Avatar answered Nov 02 '22 04:11

Philipp