# Increment matrix structure in MongoDb

I would like to have a matrix structure (a NxN integer matrix) and I want to increment values in it. Which is the right approach to model a matrix in MongoDb and to increment theirValues?

## Answers

Lets consider we have:

1 2 3 4 5 6 7 8 9

You can store matrix as embedded array in mongodb in different ways:

1.Represent matrix as one-dimensional array and store like this:

{ _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 increment third element of matrix you will need following update:

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

This approach is very lightweight, because you store as minimum data as possible, but you will need always calculate position of element to update, and you will need write additional code to deserialize matrix in your driver.

2.Store matrix in following way:

{ _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 increment third element of first row in matrix you will need following update:

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

This approach should be simpler from driver side, but you will need to store more information in a database.

Choose whatever you like more.

You could use the matrix indexes 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 advantage of this approach is that you don't have to initialize the matrix, as $inc will create the fields and assign to it the value you want to increment.

You will also be able to update multiple fields at a time or create the document if it doesn't exists using upsert=true.

Last, the notation for updating is quite clean and easy :

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