Increment matrix structure in MongoDb

隐身守侯 提交于 2019-12-07 07:32:18

问题


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?


回答1:


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.




回答2:


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, ...  } }


来源:https://stackoverflow.com/questions/9235249/increment-matrix-structure-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!