如何在MongoDB中$ set子子数组项 [英] How to $set sub-sub-array items in MongoDB
问题描述
我正在开发一个Web应用程序,它具有一个类似于门户的组件(想像多个面板,可以在各个列之间进行药物处理,并进行添加或删除).我正在使用MongoDB以类似这样的格式存储此信息...
I'm developing a webapp which has a portal-ish component to it (think like multiple panels that can be drug around from column to column and added or removed). I'm using MongoDB to store this info with a format like so...
{
_id: ObjectId(...),
title: 'My Layout',
columns: [
{
order: 1,
width: 30,
panels: [
{ title: 'Panel Title', top: 100, content: '...' },
{ title: 'Panel Title', top: 250, content: '...' },
]
},
{
... multiple columns ...
}
]
}
我正在尝试对 update()使用原子/修饰符操作,这令人困惑.如果我只想更新特定面板的一个属性,该如何引用?
I'm attempting to use atomic/modifier operations with update() and this is getting confusing. If I wanted to just update one property of a specific panel, how do I reference that?
update(
{ _id: ObjectId(...) },
{ $set: { columns.[???].panels.[???].top: 500 }
)
推荐答案
如果您知道数组中的索引,则可以使用点符号直接访问数组元素.
If you know the index in the array you can access the array element directly using dot notation.
update(
{ _id: ObjectId(xxxx) },
{ $set: { 'columns.0.panels.0.top' : 125}}
)
确保将引号中的点号路径括在字符串中.
Make sure you encase the dot notated path in quotes as a string.
要提供有关如何动态运行的更多详细信息,我将在PHP中给出一个示例:
To give more detail on how this could work dynamically, I'll give an example in PHP:
$action = array("columns.$colNum.panels.$panelNum" => $newValue);
是的,有位置运算符,但是似乎不够高级来更改数组在数组中,这在MongoDB 1.7.0中可能会更改
Yes there is the positional operator, but it does not appear to be advanced enough to change arrays within arrays, this may change in MongoDB 1.7.0
您可以执行另一种方法,而不是尝试将这些信息填充到嵌套文档中.尝试将其弄平.您可以创建一个包含面板&列对象:
There is an alternative you can do instead of trying to stuff this information into a nested document. Try to flatten it out. You can create a collection that has panel & column objects:
列对象:
{
_id: // MongoId
type: 'column',
user: 'username',
order: 1,
width: 30,
}
面板对象:
{
_id: //MongoId
type: 'panel',
user: 'username',
parentColumn: //the columns _id string
top: 125,
left: 100
}
然后您可以通过执行以下操作找到属于用户的所有列:
Then you can find all columns that belong to a user by doing:
find({ type: 'column', user:'username'});
您可以通过执行以下操作找到特定列的所有面板:
You can find all panels for a specific column by doing:
find({type: 'panel', columnOwner:'ownerID'});
由于每个列和面板都有MongoDB为其赋予的唯一ID,因此您可以轻松查询和自动设置选项.
Since each column and panel will have a unique ID given by MongoDB to it, you can easily query and atomically set options.
update({'_id': ObjectId('idstring')}, {$set : { 'top' : 125}});
这篇关于如何在MongoDB中$ set子子数组项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!