我在更新时使用$ set和$ inc做错了什么

时间:2012-05-27 10:14:17

标签: mongodb

我在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
}

如果doc不存在,则创建一个计数为1.否则,只需增加计数。为什么不在上面工作?

3 个答案:

答案 0 :(得分:16)

在我看来,您的代码实际上是尝试设置文档的$ inc字段,而不是在foo.count字段上使用$ inc修饰符。这可能是你想要的:

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

希望这有帮助。

答案 1 :(得分: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);

答案 2 :(得分:0)

所以我现在正在尝试:

var doc = {
            "name": "thename",
            "organisation": "theorganisation"
        }, // document to update. Note: the doc here matches the existing array
    query = { "email": "email@example" }; // 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@example" });

这将更新score,并将其添加到对象(如果它不存在),但它似乎将所有对象name更改为doc.name(即此处的“thename”)情况)。

如果文档尚不存在,我还没有进入