MongoDb中的增量矩阵结构 [英] Increment matrix structure in MongoDb

查看:200
本文介绍了MongoDb中的增量矩阵结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想拥有一个矩阵结构(一个NxN整数矩阵),我想增加其中的值.在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?

推荐答案

让我们考虑一下:

1 2 3
4 5 6
7 8 9

您可以通过不同的方式将矩阵作为嵌入式数组存储在mongodb中:

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

1.将矩阵表示为一维数组并像这样存储:

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.按以下方式存储矩阵:

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.

这篇关于MongoDb中的增量矩阵结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆