$ set和$ inc在更新中我在做什么错 [英] What am I doing wrong with $set and $inc in update

查看:94
本文介绍了$ set和$ inc在更新中我在做什么错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 mongodb控制台中尝试此操作:

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

返回"ok",但db.foobar.find(),返回空记录集.我正在尝试upsert一个文档,所以它看起来像:

It returns with "ok", but db.foobar.find(), returns an empty record set. I'm trying to upsert a document, so it looks like the:

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

如果该文档不存在,则创建一个计数为1的文档.否则,只需增加计数即可.为什么上面的方法不起作用?

If the doc doesn't exist then create one with a count of 1. Otherwise, just increase the count. Why isn't above working?

推荐答案

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

It seems to me that your code is actually trying to set the $inc field of the document rather than using the $inc modifier on the foo.count field. This might be what you want:

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

希望这会有所帮助.

这篇关于$ set和$ inc在更新中我在做什么错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆