2012-05-27 24 views
8

我想這在mongodb console

db.foobar.update( 
    { name: "Foobar" }, 
    { 
    $set : { foo: { bar: 'bar' }, 
    $inc: { 'foo.count': 1 } 
    } 
}, true) 

它返回一個「OK」,但db.foobar.find(),返回一個空的記錄集。我試圖upsert文件,所以它看起來像:

name: Foobar 
foo: { 
    bar: 'bar' 
    count: 1 
} 

如果文檔不存在,則創建一個具有爲1的數,否則,只是增加了計數。爲什麼上面沒有工作?

回答

7

在我看來,您的代碼實際上是在設置文檔的$ inc字段,而不是在foo.count字段中使用$ inc修飾符。這可能是你想要的:

db.foobar.update(
    { name: "Foobar" }, 
    { 
     $set: { 'foo.bar': 'bar' }, 
     $inc: { 'foo.count': 1 } 
    }, true) 

希望這會有所幫助。

+0

這是行得通的。但爲什麼不能這樣工作:'db.foobar.update({name:「Foobar」},{$ set:{foo:{bar:'bar'}},$ inc:{'foo.count':1 }},true)'似乎在字符串中的設置將使它工作。但我不知道爲什麼 –

+1

我沒有注意到! shell提供的錯誤信息是'更新中有衝突的mod'。對我來說,這表明$集合作爲一個整體在'foo'子文檔上運行,因此您不能在'foo'或其任何屬性(如'foo.count')上使用$ inc。我猜想在'foo.bar'上使用$ $,在'foo.count'上使用$ inc是可行的,因爲這兩個修飾符都是針對文檔的不相交部分。 – idrarig

1

在您提供的代碼片段中,您缺少$ set對象後的結束花括號。但這是一個側面問題。

我不相信你可以在一個事務中設置和增加同一個子文檔。 由於count是foo下的成員,因此它不會存在。當我嘗試以下錯誤時:

db.foobar.update( 
    { name: "Foobar" }, 
    { 
    $set : { foo: { bar: 'bar' }}, 
    $inc: { 'foo.count': 1 } 
    } 
}, true) 

是「更新中的衝突模塊」。 也許你可以用這種方式進行建模的:

db.foobar.update({name:"foobar"},{$set:{foo:{bar:"bar"}},$inc:{count:1}},true); 

或者如果你喜歡:

db.foobar.update({name:"foobar"},{$set:{foo:{bar:"bar"}},$inc:{"counts.foo":1}},true); 
0

所以我目前正在:

var doc = { 
      "name": "thename", 
      "organisation": "theorganisation" 
     }, // document to update. Note: the doc here matches the existing array 
    query = { "email": "[email protected]" }; // query document 
    query["history.name"] = doc.name; // create the update query 
    query["history.organisation"] = doc.organisation; 
    var update = db.getCollection('users').findAndModify({ 
     "query": query, 
     "update": { 
      "$set": { 
       "history.$.name": doc.name, 
       "history.$.organisation": doc.organisation 
      }, 
      "$inc": { "history.$.score": 5 } //increment score 
     } 
    }); 
    if (!update) { 
     db.getCollection('users').update(
      { "email": query.email }, 
      { "$push": { "history": doc } } 
     ); 
    } 
    db.getCollection('users').find({ "email": "[email protected]" }); 

此更新score,並將其添加如果該對象不存在,但它似乎將所有對象name s更改爲doc.name(即本例中的「名稱」)。

如果文檔還不存在,我還沒有着手