Upsert with $in

喜你入骨 提交于 2019-12-07 19:12:14

问题


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']

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 (

{'_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.

Any ideas on this?


回答1:


Certainly does work :

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

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 )

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.



来源:https://stackoverflow.com/questions/15198336/upsert-with-in

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!