2017-04-11 120 views
0
{ 
    "doc_id": 1234, 
    "pars": [ 
     { 
     "par_id": 4567, 
     "someNode": "...", 
     "lines": [ 
      { 
      "line_id": 8901, 
      "someOtherNode": "...", 
      "text": "Foo" 
      }, 
     ] 
     } 
    ] 
} 

我怎樣才能在正確的節點知道doc_idpar_idline_id更新text領域的節點?匹配和更新根據其內容

我不能使用此查詢,因爲我不具有對應於par_idline_id

con.db.col.update(
    {'_id': doc_id}, 
    {'$set': { "pars.?.lines.?.text": "Bar" } } 
) 
+0

可能欺騙http://stackoverflow.com/questions/30019015/update-nested-array-document – chridam

+0

另外值得跟蹤JIRA https://jira.mongodb.org/browse/SERVER-831 – chridam

回答

-1

,你可以不喜歡這個 -

db.col.update(
    {"_id": doc_id, "par_id": 4567, "pars.lines.line_id":8901}, 
    {$set: { "pars.$.lines.$.text":"ANY_TEXT_YOU_WANT" } }, 
function(){} //callback function) 
+0

不,不支持兩個「$」操作符。 –

+0

OOPS使用這個 - : '{$ set:{「pars.lines。$。text」:「ANY_TEXT_YOU_WANT」}} – hardy

0

Because updating based on a match in nested arrays is not yet supported in MongoDB節點索引,你」你需要重新安排你的模式。現在你有一個段落數組,每個段落都是一行數組。我建議製作段落號爲的文檔,其字段名爲paragraphIds,而不是數組。你可以保持行作爲一個數組,你可以通過paragraphId和lineId使用"$" positional operator然後更新:

> db.collection.insertOne({ 
... "doc_id": 1234, 
... "pars": { 
...  4567: { 
...  "someNode": "...", 
...  "lines": [ 
...   { 
...   "line_id": 8901, 
...   "someOtherNode": "...", 
...   "text": "Foo" 
...   }, 
...  ] 
...  } 
... } 
... }) 
{ 
    "acknowledged" : true, 
    "insertedId" : ObjectId("58ecb95e475838c0db6efd9d") 
} 
> db.collection.updateOne({ 
... "doc_id": 1234, 
... "pars.4567.lines.line_id": 8901 
... }, { 
... "$set": {"pars.4567.lines.$.text": "Bar"} 
... }) 
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 } 
> db.collection.findOne({"doc_id": 1234}) 
{ 
    "_id" : ObjectId("58ecb95e475838c0db6efd9d"), 
    "doc_id" : 1234, 
    "pars" : { 
    "4567" : { 
     "someNode" : "...", 
     "lines" : [ 
     { 
      "line_id" : 8901, 
      "someOtherNode" : "...", 
      "text" : "Bar" 
     } 
     ] 
    } 
    } 
} 
-1

$$是特殊的運算符(新位置運營商)

你可以做這樣的事情 -

db.col.update(
    {"_id": doc_id, "par_id": 4567, "pars.lines.line_id":8901}, 
    {$set: { "pars.lines.$$.text":"ANY_TEXT_YOU_WANT" } }, 
function(){} //callback function)