0

我有一个集合'locations',我想用'united+states'替换'usa'。DB的现状如下:

> db.locations.find({'country':'usa'})
{ "_id" : "boston", "country" : [ "usa" ], "server" : "", "ts" : 1369642586.077319, "type" : [ "city" ] }
{ "_id" : "chicago", "country" : [ "usa" ], "server" : "", "ts" : 1369642589.226037, "type" : [ "city" ] }
{ "_id" : "las+vegas", "country" : [ "usa" ], "server" : "", "ts" : 1369642591.688284, "type" : [ "city" ] }
{ "_id" : "los+angeles", "country" : [ "usa" ], "server" : "", "ts" : 1369642601.672113, "type" : [ "city" ] }
{ "_id" : "miami", "country" : [ "usa" ], "server" : "", "ts" : 1369642606.281971, "type" : [ "city" ] }
{ "_id" : "new+york", "country" : [ "usa" ], "server" : "", "ts" : 1369642611.884712, "type" : [ "city" ] }
{ "_id" : "portland", "country" : [ "usa" ], "server" : "", "ts" : 1369642615.59296, "type" : [ "city" ] }
{ "_id" : "san+francisco", "country" : [ "usa" ], "server" : "2", "ts" : 1369642619.255885, "type" : [ "city" ] }
{ "_id" : "san+jose", "country" : [ "usa" ], "server" : "", "ts" : 1369642622.74329, "type" : [ "city" ] }
{ "_id" : "seattle", "country" : [ "usa" ], "server" : "", "ts" : 1369642625.195549, "type" : [ "city" ] }
{ "_id" : "washington+dc", "country" : [ "usa" ], "server" : "", "ts" : 1369642628.37334, "type" : [ "city" ] }
{ "_id" : "cleveland", "country" : [ "usa" ], "server" : "2", "ts" : 1369642634.523065, "type" : [ "city" ] }
{ "_id" : "columbus", "country" : [ "usa" ], "server" : "2", "ts" : 1369642636.874618, "type" : [ "city" ] }
{ "_id" : "dallas", "country" : [ "usa" ], "server" : "2", "ts" : 1369642639.080141, "type" : [ "city" ] }
{ "_id" : "denver", "country" : [ "usa" ], "server" : "2", "ts" : 1369642642.236581, "type" : [ "city" ] }
{ "_id" : "houston", "country" : [ "usa" ], "server" : "2", "ts" : 1369642644.783804, "type" : [ "city" ] }
{ "_id" : "minneapolis", "country" : [ "usa" ], "server" : "2", "ts" : 1369642647.153817, "type" : [ "city" ] }
{ "_id" : "nashville", "country" : [ "usa" ], "server" : "2", "ts" : 1369642650.497276, "type" : [ "city" ] }
{ "_id" : "new+orleans", "country" : [ "usa" ], "server" : "2", "ts" : 1369642653.584663, "type" : [ "city" ] }
{ "_id" : "philadelphia", "country" : [ "usa" ], "server" : "2", "ts" : 1369642656.524054, "type" : [ "city" ] }

我运行了以下 MongoDB 查询,这应该可以解决问题:

db.locations.update({'country':'usa'}, {'$set': {'country.$': 'united+states'}}, multi=true)

但是,这并没有达到预期的效果,并且 Collection 文档仍然有 'usa' 而不是 'united+states'。

4

2 回答 2

1

看起来您的更新调用中有错字,请尝试以下操作:

db.locations.update({'country':'usa'}, {'$set': {'country.$': 'united+states'}}, {multi:true})

注意:选项现在{multi:true}而不是multi=true(或只是true

于 2013-05-27T11:17:12.930 回答
0

更新多个数组元素是不可能的,检查这个答案MongoDB 更新数组的多个记录,如果它们是正确的,这可能会起作用

db.locations.find().forEach(function(doc) { 
    do { 
       db.locations.update({'country' : 'usa'}, 
       { $set : {'country.$' : 'united states'}}, true); 
    } while(db.getPrevError().n != 0); 
});
于 2013-05-27T08:50:11.447 回答