2015-10-20 118 views
0

什麼是查詢更新以下數據與貓鼬。所以3個領域將被更新。頂級父點,類別點和標記點。貓鼬,更新孩子會影響所有父母嗎?

{ 
"_id": "561fba5e7fac41a4055fad45", 
"fullName": "Test", 
"points": 45, 
"level": 1, 
"categories": [ 
    { 
    "name": "Computer Science", 
    "points": 15, 
    "level": 1, 
    "_id": "561fba5e7fac41a4055fad46", 
    "tags": [ 
     { 
     "name": "C#", 
     "points": 10, 
     "level": 1, 
     "_id": "561fba5e7fac41a4055fad47" 
     }, 
     { 
     "name": "Java", 
     "points": 5, 
     "level": 1, 
     "_id": "561fba5e7fac41a4055ert12" 
     } 
    ] 
    }, 
    { 
    "name": "History", 
    "points": 30, 
    "level": 2, 
    "_id": "562407d4e3edf2113f61ac37", 
    "tags": [ 
     { 
     "name": "WW2", 
     "points": 30, 
     "level": 2, 
     "_id": "56240797e3edf2113f61ac36" 
     } 
    ] 
    } 
] 
} 

到這個。當用戶從特定標籤獲得一個點時,它會影響所有家長。比方說,用戶從C#中獲得10分,那麼我必須更新mongodb。

{ 
"_id": "561fba5e7fac41a4055fad45", 
"fullName": "Test", 
**"points": 55,** 
"level": 1, 
"categories": [ 
    { 
    "name": "Computer Science", 
    **"points": 25,** 
    "level": 1, 
    "_id": "561fba5e7fac41a4055fad46", 
    "tags": [ 
     { 
     "name": "c#", 
     **"points": 20,** 
     "level": 1, 
     "_id": "561fba5e7fac41a4055fad47" 
     }, 
     { 
     "name": "Java", 
     "points": 5, 
     "level": 1, 
     "_id": "561fba5e7fac41a4055ert12" 
     } 
    ] 
    }, 
    { 
    "name": "History", 
    "points": 30, 
    "level": 2, 
    "_id": "562407d4e3edf2113f61ac37", 
    "tags": [ 
     { 
     "name": "WW2", 
     "points": 30, 
     "level": 2, 
     "_id": "56240797e3edf2113f61ac36" 
     } 
    ] 
    } 
] 
} 
+0

通過蒙戈MongoDB中[更新嵌套的數組的可能的複製shell](http://stackoverflow.com/questions/18573117/updating-nested-arrays-in-mongodb-via-mongo-shell) – chridam

+0

[更新MongoDB中數組中所有元素]的可能副本(http:// stackoverflow.com/questio ns/33186596/update-all-elements-in-an-array-in-mongodb) – styvane

+0

這些並不重複,因爲我試圖增加所有頂級父字段。 @ user3100115 –

回答

1

你應該使用$elemMatch查詢您的對象

db.tests.update({_id: yourTestId, categories: {$elemMatch: {_id: categoryId}}}, {$set: {$inc: {"categories.$.points": 10, points: 10}}}) 

所以你查詢只需要數組元素和更新與$參考值

+1

{$ inc} does not work out @vmkcom This works db.users.update({categories:{$ elemMatch:{name:「Sport」}}},{$ inc :{「categories。$。points」:6666,points:7777}}) –

+0

ofc,@YagizOzturk,忘記了操作員的訂單。 – vmkcom

+0

感謝您的回答,真的幫了我。但是第二個孩子是C#呢?有沒有辦法在同一個查詢中更新它的觀點?在你的例子中,它不會遞增@ vmkcom –

相關問題