MongoDB更新很多有条件的

时间:2019-05-12 11:59:18

标签: mongodb mongodb-query

我有一个带有各种不一致的大数据库。我要清除的项目之一是根据人口数量更改国家/地区身份。

数据样本为:

{ "_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字段。

我尝试过这种方法,但显然缺少某种与国家/地区字段更新相关的方法。

db.country.updateMany( { case : { $lt : ["$pop" : 20000000] }, then : "Small country" }, { case : { $gte : ["$pop" : 20000000] }, then : "Large country" }

编辑:在完成写作之前发布。

我当时在考虑使用$cond功能,以便在使用updateMany时基本上返回true,如果是,则返回X,否则返回y。

这可能吗,还是有解决方法?

1 个答案:

答案 0 :(得分:3)

您确实希望bulkWrite()内使用两个"updateMany"语句。聚合表达式不能用于任何形式的update语句中的“替代选择”。

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是在提出此请求后引入的,并且确实可以适应,如所示的或多或少是同一件事。

还建议在聚合语句中使用$out,否则不是“ update” 的选项,并且目前只能写入“新集合”。从MongoDB 4.2开始的预定更改将允许$out实际上“更新” 现有集合, 但是 要更新的集合与从聚合管道收集数据时使用的任何其他集合都不相同。因此,不可能使用汇总管道来更新与您正在读取的内容相同的相同集合

简而言之,请使用bulkWrite()