0

Let's assume this structure

class A
{
  string Id;
  int value
  ...
}

and

class B
{
    int sum;
    List<A> L;
    some stuff
}

I have a Mongo table with objects B

What I need to do is the following, in pseudo code:

if (any A item of B has Id == XXX)
{
  if (A.value > X)
  {
    B.Sum += A.Value;
    A.Value = 0;
  }
}

in one (atomic) operation.

The B.sum += A.Value and the A.Value = 0 need to be atomic.

I have absolutely no clue on how to implement that.

Has anyone done something similar with MongoDB before?

Thomas
  • 10,933
  • 14
  • 65
  • 136

1 Answers1

0

As you probability know Mongo does not have transaction. But in your case I think it is easy to work around if you use a noSql approach. All you need to so is have a single table of B object where the A objects are included inside the array:

a B object { sum: 0, listA: [ {id: A1, value: 1}, {id: A2, value:2 }], some stuff }

Then you query for A object do: db.B.find({"listA.id":"XXX"})

You do calculations on B object and then you only need to update one B record - and that is atomic

This is better explained here How to work around the lack of transactions in MongoDB?.