Increasing matrix structure in MongoDb

I would like to have a matrix structure (NxN integer matrix), and I want to increase the values ​​in it. What is the correct approach to modeling the matrix in MongoDb and to increase their values?

+4
source share
2 answers

Suppose we have:

1 2 3 4 5 6 7 8 9 

You can store the matrix as an inline array in mongodb in different ways:

1.Represent matrix as a one-dimensional array and save it as follows:

 { _id: "1", matrix: [1,2,3,4,5,6,7,8,9], width: 3, // or store just size in case of NxN height: 3, } 

Then, to increase the third matrix element, you need the following update:

 db.matrix.update({_id: 1}, { $inc : { "matrix.2" : 1 } } 

This approach is very easy, because you save as little data as possible, but you always need to calculate the position of the element for updating, and you will need to write additional code to deserialize the matrix in your driver.

2. Store the matrix as follows:

 { _id: "1", matrix: [ {xy: "0-0", v: 1}, {xy: "1-0", v: 2}, {xy: "2-0", v: 3}, {xy: "0-1", v: 4}, ... ] } 

Then, to increase the third element of the first row in the matrix, you need the following update:

 db.matrix.update({_id: 1, "matrix.xy": 2-0 }, { $inc : { "matrix.$.v" : 1 } } 

This approach should be easier on the driver side, but you will need to store more information in the database.

Choose what you like best.

+5
source

You can use matrix indices as field names:

 { _id: "1", matrix: { "0": {{"0": 0}, {"1": 0}, {"2": 0}} "1": {{"0": 0}, {"1": 0}, {"2": 0}}, "2": {{"0": 0}, {"1": 0}, {"2": 0}}, "3": {{"0": 0}, {"1": 0}, {"2": 0}}, ... ] } 

One of the advantages of this approach is that you do not need to initialize the matrix, since $inc will create the fields and assign it the value you want to increase.

You can also update several fields at once or create a document if it does not exist using upsert=true .

Finally, the update notation is pretty clean and simple:

 db.matrix.update({_id: 1}, { $inc : { "matrix.0.0" : 1, "matrix.0.1" : 2, ... } } 
0
source

Source: https://habr.com/ru/post/1395846/


All Articles