Update a document based on other documents in atomically

Hello,
I have a collection with parent objects and children objects. The relationships are defined by the “ownerId” field, that links children with their parent.
For example the collection structure could be:

[{
  "id": 45842,
  "ownerId": 45842,
  "processing": true
},{
  "id": 45850,
  "ownerId": 45842,
  "processing": false
},{
  "id": 46095,
  "ownerId": 45842,
  "processing": true
},{
  "id": 46096,
  "ownerId": 45842,
  "processing": false
}]

I need to update the derived “processing” field of the parent object based on the “processing” field of its children: if all cildren have “processing” false then the parent “processing” field must be false, otherwise must be true.
We have written this:

db["azure-objects"].updateOne(
    { id: 45842 },
    [
        { $set: { processing: db['azure-objects'].aggregate(
            [
                { $match: { ownerId: 45842, id: { $ne: 45842 } } },
                { $group: { _id: "$ownerId", processing: { $max: "$processing" } } },
                { $project: { "_id": 0 } }
            ]
            ).next()["processing"] } }
    ]
);

The question is: is it atomic? Can i improve it? Or i need to wrap it in a transaction?

Thanks in advance.
Stefano

The reason transactions exist as a design pattern since the 1960’s or 1970’s is that figuring out all the ways a sequence of database operations can unexpectedly become non-atomic requires knowledge of (often undocumented) internals. If your question is, “How to I guarantee that this compound operation will be atomic?” then the answer is, “make it a transaction.”

4 Likes

Thanks for the reply! I figured the most immediate solution is to use a transaction but, since I’m using camel-mongodb, if it was possible to use a single atomic operation for me it would have been easier.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.