选择并更新MongoDB中的子文档

时间:2015-02-08 10:26:49

标签: mongodb meteor

我在MongoDB集合中有以下文档结构:

[
    {
        "cells": [
            {
                "x": 0,
                "y": 0,
                "classes": "head"
            },
            {
                "x": 1,
                "y": 0,
                "classes": "head"
            }
        ],
        "_id": "5AWuNaYaB7Sox4mvp"
    },
    {
        "cells": [
            {
                "x": 0,
                "y": 1,
                "classes": "head"
            },
            {
                "x": 1,
                "y": 1,
                "classes": "head"
            }
        ],
        "_id": "qKu3fvdJZ4JedMwMj"
    }
]

它是我在Meteor应用程序中使用的表。

这些是我的模板:

<template name="table">
    <table>
            {{#each rows}}
                    {{> tableRow}}
            {{/each}}
    </table>
</template>

<template name="tableRow">
    <tr>
            {{#each cells}}
                    {{> tableCell}}
            {{/each}}
    </tr>
</template>

<template name="tableCell">
    <td class="{{classes}}"></td>
</template>

这是我的帮手:

Template.table.helpers({
    rows: function() {
            return Table.find();
    }
});

这一切都很好。它正确地创建了一个2x2表,其中所有单元格都具有&#34; head&#34; class,占位符。完成后,它将至少有50x50个细胞

我的问题是:如何在不返回整行的情况下使mongo查询返回一个特定单元格?我的结果应该只是

{x: 0, y: 0, classes: "head"}

我还想从文档中删除x和y属性,并使用文档中的位置隐式给出x和y,就像用[y] [x]查找多维数组一样。 / p>

更重要的是,但我想与查找单元格对象有关,正在更新单元格对象。能否请举例说明如何更新&#34;类&#34;细胞(1,1)的性质?

我也开放重组整个事情,但我想在整个事情中只需要一个find() - 命令。该表将经常更新,例如每秒几次。我尝试为每一行使用一个find(),并使用不同的文档结构。它工作正常,我可以轻松查询和更新每个单元格,但每个查询在50x50表格上返回需要2秒钟。

1 个答案:

答案 0 :(得分:1)

我会将每个单元格存储在自己的文档中:

{
    "x" : 0,
    "y" : 2,
    "classes" : "head"
}

要查找一个单元格,请按xy进行查找。

db.cells.find({ "x" : 1, "y" : 3 })

要更新单元格,请按xy查找并更新。

db.cells.update({ "x" : 1, "y" : 2 }, { "$set" : { "classes" : "tails" } })

要查找&#34;二维数组顺序&#34;中的所有单元格,请对{ "x" : 1, "y" : 1 }进行排序。

db.cells.find({},{&#34; _id&#34;:0,&#34; classes&#34;:1})。sort({&#34; x&#34;:1 ,&#34; y&#34;:1})

结果集中的位置隐式提供xy - 您可以编写一个函数来计算xy的位置i排序结果中的单元格,基于知道表格的尺寸。

我不认为它出现在问题中,但也很容易找到整行或列:

db.cells.find({ "x" : 0 })
db.cells.find({ "y" : 2 })

编辑如何在原始文档结构中查找和更新一个单元格

使用$elemMatch projection

db.cells.find({ "_id" : "5AWuNaYaB7Sox4mvp" }, { "cells" : { "$elemMatch" : { "x" : 0, "y" : 1 } } })

db.cells.update({ "_id" : "5AWuNaYaB7Sox4mvp", "cells" : { "$elemMatch" : { "x" : 0, "y" : 1 } }, { "$set" : { "cells.$.classes" : "tails" } })