Select 并更新 MongoDB 中的子文档

Select and update subdocument in MongoDB

我在 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 应用程序中使用的 table。

这些是我的模板:

<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 table,其中所有单元格都有 "head" class,这是一个占位符。完成后,它将至少有 50x50 个单元格

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

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

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

更重要的是,但我想与查找单元格对象相关的是更新单元格对象。您能否举例说明如何更新单元格 (1, 1) 的 "classes" 属性?

我也愿意重组整个事情,但我只想在整个事情中使用一个 find() 命令。 table 会经常更新,比如每秒几次。我尝试为每一行设置一个 find(),具有不同的文档结构。它工作正常,我可以轻松查询和更新每个单元格,但在 50x50 table.

上每次查询 return 需要 2 秒

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

{
    "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" } })

要查找 "two-dimensional array order" 中的所有单元格,请按 { "x" : 1, "y" : 1 } 排序。

db.cells.find({ }, { "_id" : 0, "classes" : 1 }).sort({ "x" : 1, "y" : 1 } )

结果集中的位置隐式给出xy——你可以写一个函数从位置[=24=计算xy ] 排序结果中的单元格,基于了解 table.

的维度

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

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" } })