2010-08-13 37 views
8

我正在開發一個web應用程序,它有一個portal-ish組件(像多個面板一樣,可以是從列到列的藥物,添加或刪除)。我使用MongoDB的存儲與像這樣的格式此信息...

{ 
    _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(
    { _id: ObjectId(...) }, 
    { $set: { columns.[???].panels.[???].top: 500 } 
) 

回答

14

如果您知道數組中的索引,則可以使用點符號直接訪問數組元素。

update(
{ _id: ObjectId(xxxx) }, 
{ $set: { 'columns.0.panels.0.top' : 125}} 
) 

請確保您將引號中的點符號路徑包含爲字符串。

編輯:

要查看關於如何可以動態地工作更詳細,我會在PHP舉個例子:

$action = array("columns.$colNum.panels.$panelNum" => $newValue); 

是存在positional operator,但它does not appear to be advanced enough改變數組中的數組,這可能會在MongoDB中更改1.7.0

還有一種方法可以替代嘗試將此信息填充到嵌套文檔中。嘗試平坦化。你可以創建一個具有面板&列對象的集合:

列對象:

{ 
_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 
} 

然後你就可以發現,通過做屬於用戶所有列:

find({ type: 'column', user:'username'}); 

您可以通過執行以下操作找到特定列的所有面板:

find({type: 'panel', columnOwner:'ownerID'}); 

由於每一列和麪板將通過MongoDB的給它一個唯一的ID,您可以輕鬆地查詢並自動設置選項。

update({'_id': ObjectId('idstring')}, {$set : { 'top' : 125}}); 
+0

我不知道這一點。對指標進行硬編碼確實不可行。仍試圖找出如何使用位置運算符http://www.mongodb.org/display/DOCS/Updating#Updating-The%24positionaloperator – Dex 2010-08-14 16:46:59

+0

添加更多詳細信息 – Klinky 2010-08-15 00:28:12

0

我也有這樣的情況,我在$ pull之後跟着$ addToSet替換即更新我需要的東西。

update(
{ _id: ObjectId(...) }, 
{ $addToSet: { columns.$.panels : "new sub-Doc" } 
) 

,然後取下舊值

update({_id:ObjectId(....)},{$pull : { columns.$.panels : {"top" : 100} }}) 
+0

列上的$ for是多少? – 2016-08-07 19:39:25

+0

「$」充當佔位符以更新與更新中的查詢條件相匹配的第一個元素。請參閱https://docs.mongodb。COM /手動/參考/操作員/更新/位置/#up._S_ – achuth 2016-08-09 09:30:56

相關問題