MongoDB更新很多有条件的 [英] MongoDB updateMany with Conditional
问题描述
我有一个带有各种不一致之处的大型数据库.我要清除的项目之一是根据人口数量更改国家/地区身份.
I have a large DB with various inconsistencies. One of the items I would like to clear up is changing the country status based on the population.
数据样本为:
{ "_id" : "D", "name" : "Deutschland", "pop" : 70000000, "country" : "Large Western" }
{ "_id" : "E", "name" : "Eire", "pop" : 4500000, "country" : "Small Western" }
{ "_id" : "G", "name" : "Greenland", "pop" : 30000, "country" : "Dependency" }
{ "_id" : "M", "name" : "Mauritius", "pop" : 1200000, "country" : "Small island"}
{ "_id" : "L", "name" : "Luxembourg", "pop" : 500000, "country" : "Small Principality" }
很明显,我想根据人口数量来更改Country字段.
Obviously I would like to change the country field go something more uniform, based on population size.
我尝试过这种方法,但显然缺少某种与国家/地区字段更新相关的方法.
I've tried this approach, but obviously missing some way of tying into an update of the country field.
db.country.updateMany( { case : { $lt : ["$pop" : 20000000] }, then : "Small country" }, { case : { $gte : ["$pop" : 20000000] }, then : "Large country" }
在完成写作之前发布.
我当时正在考虑使用$cond
功能,以便在使用updateMany时基本上返回true,x,false,y.
I was thinking to use $cond
functionality, to basically return if true, do X, if false, do y, while using the updateMany.
这可能吗,还是有解决方法?
Is this possible, or is there a workaround?
推荐答案
您确实想要语句.聚合表达式不能用于任何形式的update语句中的替代选择".
You really want want bulkWrite()
using two "updateMany"
statements within it instead. Aggregation expressions cannot be used to do "alternate selection" in any form of update statement.
db.country.bulkWrite([
{ "updateMany": {
"filter": { "pop": { "$lt": 20000000 } },
"update": { "$set": { "country": "Small Country" } }
}},
{ "updateMany": {
"filter": { "pop": { "$gt": 20000000 } },
"update": { "$set": { "country": "Large Country" } }
}}
])
SERVER-6566 上仍存在一个突出的功能请求",用于条件句法",但这尚未解决.实际上,批量" API是在提出此请求后引入的,并且确实可以适应,如所示或多或少是同一件事.
There is still an outstanding "feature request" on SERVER-6566 for "conditional syntax", but this is not yet resolved. The "bulk" API was actually introduced after this request was raised, and really can be adapted as shown to do more or less the same thing.
还在聚合语句中使用 $out
作为否则建议不是更新" 的选项,并且目前只能写入新集合".从MongoDB 4.2起的预定更改将允许 $out
实际上是更新" 现有集合, 但是 来自聚合管道的数据.因此,不可能使用汇总管道来更新与您正在读取的内容相同的相同集合.
Also using $out
in an aggregation statement as was otherwise suggested is not an option to "update" and can only write to a "new collection" at present. The slated change from MongoDB 4.2 onwards would allow $out
to actually "update" an existing collection, however this would only be where the collection to be updated is different from any other collection used within the gathering of data from the aggregation pipeline. So it is not possible to use an aggregation pipeline to update the same collection as what you are reading from.
简而言之,请使用 bulkWrite()
.
In short, use bulkWrite()
.
这篇关于MongoDB更新很多有条件的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!