执行此类操作的最简单方法是在数据集中循环,重新映射字段的名称.最简单的方法是编写一个执行重写的函数,然后在shell中使用.find().forEach()
语法.
下面是一个贝壳样品:
db.foo.save({ a : 1, b : 2, c : 3});
db.foo.save({ a : 4, b : 5, c : 6});
db.foo.save({ a : 7, b : 8 });
db.foo.find();
remap = function (x) {
if (x.c){
db.foo.update({_id:x._id}, {$set:{d:x.c}, $unset:{c:1}});
}
}
db.foo.find().forEach(remap);
db.foo.find();
在上面的例子中,我在同一个动作中做$unset
和$set
.MongoDB不支持跨集合的事务,但上面是一个文档.所以你可以保证set和unset是原子的(i.e. they both succeed or they both fail).
这里唯一的限制是,您需要管理外部写入程序以保持数据的一致性.我通常倾向于在更新时关闭写操作.如果此选项不可用,则必须确定数据的一致性级别.(我可以在这里提供一些 idea ,但它将真正针对您的数据和系统)