0

I'm looking to a way to optimise data by regrouping and ungrouping fields from sub documents.

Example: I want to add a subdocument:

{
    field2: "B",
    field3: "D"     
}

in the array "children" of an existing document in a collection:

{
field1: "A",
children: [
    {
       field2: "B",
       field3: "C"     
    }
]
}

And so will be the result I want (because the two children have the same field2 value):

{
field1: "A",
field2: "B",
children: [
    {
       field3: "C"     
    },
    {
       field3: "D"
    }
]
}

Alternatively if I want to add a new subdocument like:

{
field2: "B",
field3: "D"
}     

The result will be:

{
field1: "A",
children: [
    {
       field2: "B",
       field3: "C"     
    },
    {
       field2: "B",
       field3: "D"
    },
    {
       field2: "E",
       field3: "F"
    }

]
}

I can do it in the Java backend server by finding the parent document and process it but I will have to check multiple concurrent access (multiple request to add subdocument at the same time). That's why I m looking for a way to do it directly in the database at the insert time.

Thanks!

Saveriu CIANELLI
  • 510
  • 5
  • 17
  • Check if [this](https://stackoverflow.com/questions/29704284/how-do-i-execute-a-mongodb-js-script-using-the-java-mongodriver) meets your requirements – Valijon Mar 06 '20 at 14:35
  • Hi thanks for the link, I will investigate. Is this equivalent to do the same thing in Java or do we have a kind of "transaction" with server script? – Saveriu CIANELLI Mar 09 '20 at 09:08

0 Answers0