我有一个大型数据库,其中存在各种不一致之处。我想澄清的项目之一是根据人口更改国家/地区状态。
数据样本是:
{ "_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" }
显然,我想根据人口规模将国家/地区字段更改为更统一的内容。
我试过这种方法,但显然缺少一些绑定(bind)到国家字段更新的方法。
db.country.updateMany( { case : { $lt : ["$pop" : 20000000] }, then : "Small country" }, { case : { $gte : ["$pop" : 20000000] }, then : "Large country" }
编辑:在我写完之前发布。
我在考虑使用 $cond
功能,如果为真则基本上返回,执行 X,如果为假则执行 y,同时使用 updateMany。
这可能吗,或者有解决方法吗?
最佳答案
你真的很想很想bulkWrite()
在其中使用两个 "updateMany"
语句。聚合表达式不能用于任何形式的更新语句中的“替代选择”。
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
在另外建议的聚合语句中不是 “更新” 的选项,目前只能写入“新集合”。从 MongoDB 4.2 开始的预定更改将允许 $out
实际上“更新”一个现有的集合,但是这只会是要更新的集合与该集合中使用的任何其他集合不同的地方从聚合管道收集数据。因此,不可能使用聚合管道来更新与您正在读取的内容相同的集合。
简而言之,使用bulkWrite()
.
关于MongoDB updateMany 有条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56099018/