MongoDB - 添加到集合并递增 [英] MongoDB - Adding to a set and incrementing

查看:55
本文介绍了MongoDB - 添加到集合并递增的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 MongoDB 计算单词使用情况.我的收藏目前看起来像这样:

I am trying to count word usage using MongoDB. My collection currently looks like this:

{'_id':###, 'username':'Foo', words:[{'word':'foo', 'count':1}, {'word':'bar', 'count':1}]}

当发布新帖子时,我将所有新词提取到一个数组中,但我试图找出将其插入到 words 数组中并在该词已存在的情况下增加计数.

When a new post is made, I extract all the new words to an array but I'm trying to figure out to upsert to the words array and increment the count if the word already exists.

在上面的例子中,例如,如果用户Foo"发布了lorem ipsum foo",我会将lorem"和ipsum"添加到用户词数组中,但增加foo"的计数.

In the example above, for example, if the user "Foo" posted "lorem ipsum foo", I'd add "lorem" and "ipsum" to the users words array but increment the count for "foo".

这可以在一个查询中实现吗?目前我正在使用 addToSet:

Is this possible in one query? Currently I am using addToSet:

'$addToSet':{'words':{'$each':word_array}}

但这似乎并没有提供任何增加字数的方法.

But that doesn't seem to offer any way of increasing the words count.

非常感谢您的帮助:)

推荐答案

如果您愿意从列表切换到哈希(对象),您可以原子地执行此操作.

If you're willing to switch from a list to hash (object), you can atomically do this.

来自文档:$inc ... 如果对象中存在字段,则将字段增加数字值,否则将字段设置为数字值."

From the docs: "$inc ... increments field by the number value if field is present in the object, otherwise sets field to the number value."

{ $inc : { field : value } }

所以,如果你可以重构你的容器和对象:

So, if you could refactor your container and object:

words: [
  {
    'word': 'foo',
    'count': 1
  },
  ...
]

到:

words: {
  'foo': 1,
  'other_word: 2,
  ...
}

你可以使用 update 操作:

{ $inc: { 'words.foo': 1 } }

如果 'foo' 不存在,它将创建 { 'foo': 1 },否则增加 foo.

which would create { 'foo': 1 } if 'foo' doesn't exist, else increment foo.

例如:

$ db.bar.insert({ id: 1, words: {} });
$ db.bar.find({ id: 1 })
[ 
  {   ...,   "words" : {     },   "id" : 1   }
]
$ db.bar.update({ id: 1 }, { $inc: { 'words.foo': 1 } });
$ db.bar.find({ id: 1 })
[ 
  {   ...,   "id" : 1,   "words" : {   "foo" : 1   }   }
]
$ db.bar.update({ id: 1 }, { $inc: { 'words.foo': 1 } });
$ db.bar.find({ id: 1 })
[ 
  {   ...,   "id" : 1,   "words" : {   "foo" : 2   }   }
]

这篇关于MongoDB - 添加到集合并递增的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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