用$ in进行Upsert [英] Upsert with $in

查看:91
本文介绍了用$ in进行Upsert的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望遵循MongoDB中的功能.我有一个名为实体"的集合,该集合基本上存储实体文本并进行计数.该集合如下所示:

I want following functionality in MongoDB. I have a collection named 'entities', which basically stores entity text and it's count. The collection looks like this:

[{u'_id': u'facebook', u'n': 120},
 {u'_id': u'florida', u'n': 98},
 {u'_id': u'vegas', u'n': 94},
 {u'_id': u'andrew_mason', u'n': 93},
 {u'_id': u'obama', u'n': 85},
 {u'_id': u'twitter', u'n': 81},
 {u'_id': u'outlook', u'n': 81},
 {u'_id': u'delhi', u'n': 75},
 {u'_id': u'google', u'n': 74},
 {u'_id': u'virginia', u'n': 71}]

现在,我想用新的实体更新此收藏集.基本上,我将在这样的数组中准备好新的实体:

Now, I want to update this collection with new Entities. Basically, I'll have new entities ready in an Array like this:

entitySet = ['google', 'Abhishek_Vaid', 'andrew_mason']

我的意图是,对于已经在集合中的实体,它们的计数应被更新.至于集合中不是的实体,其计数应初始化为1.我想使用一个MongoDB查询来实现这两种效果.到目前为止,我已经能够找到以下查询:(它具有PyMongo风格,但它仍然是MongoDB查询)

My intentions are that, for the entities already in the collection their count should be updated. As for entities not in the collection, their count should be initialized to 1. I want to use a single MongoDB query to achieve both these effects. Till now I've been able to find following query : (It's in PyMongo flavor, but it's nonetheless a MongoDB query)

ENTITY_DB_HANDLE.entities.update(

ENTITY_DB_HANDLE.entities.update (

{'_id' : {'$in' : entitySet} }, {'$inc' : {'n' : 1} }, upsert=True, multi=True )

但是,此查询仅更新现有实体计数,而不会推送新实体.

However, this query only updates the existing entity counts and does not push new entities.

对此有何想法?

推荐答案

某些方法确实可行:

> db.test.save({_id:"a", n:3})
> db.test.update({_id:"b"}, {$inc:{n:1}}, true, false)
> db.test.find()
{ "_id" : "a", "n" : 3 }
{ "_id" : "b", "n" : 1 }

但是您的示例查询未使用$ in,因此我假设您实际上是在尝试:

But your example query doesn't use $in so I'm assuming you're actually trying :

{'_id' : {$in:['google', 'Abhishek_Vaid', 'andrew_mason']}, {'$inc' : {'n' : 1} }, upsert=True, multi=True )

,并期望它为您传递的每个_id值更新或创建一个条目.如果已经存在任何_id值,则此方法将不起作用,因为upsert只会创建一个新文件,而没有符合搜索条件的文件.

and expect it to update or create an entry for each _id value you pass. This will not work if any of the _id values already exists since upsert will only create a new document of no document matches the search criteria.

这篇关于用$ in进行Upsert的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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