我有一个集合'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)
然而,这并没有达到预期的效果,而且收藏文件仍然有'美国'而不是'联合+州'。
答案 0 :(得分:1)
您的更新通话中似乎有拼写错误,请尝试以下方式:
db.locations.update({'country':'usa'}, {'$set': {'country.$': 'united+states'}}, {multi:true})
注意:选项现在是{multi:true}
而不是multi=true
(或只是true
)
答案 1 :(得分:0)
无法更新多个数组元素,请查看此答案MongoDB update multiple records of array,如果正确,可能会这样做
db.locations.find().forEach(function(doc) {
do {
db.locations.update({'country' : 'usa'},
{ $set : {'country.$' : 'united states'}}, true);
} while(db.getPrevError().n != 0);
});