只需循环forEach()
并从另一列设置列值。让我们创建一个包含文档的集合-
> db.demo51.insert({"Name1":"Chris","Name":"David","Age":24}); WriteResult({ "nInserted" : 1 }) > db.demo51.insert({"Name1":"Carol","Name":"Mike","Age":22}); WriteResult({ "nInserted" : 1 }) > db.demo51.insert({"Name1":"Sam","Name":"Bob","Age":26}); WriteResult({ "nInserted" : 1 })
在find()
方法的帮助下显示集合中的所有文档-
> db.demo51.find();
这将产生以下输出-
{ "_id" : ObjectId("5e27108ccfb11e5c34d8990d"), "Name1" : "Chris", "Name" : "David", "Age" : 24 } { "_id" : ObjectId("5e27108dcfb11e5c34d8990e"), "Name1" : "Carol", "Name" : "Mike", "Age" : 22 } { "_id" : ObjectId("5e27108ecfb11e5c34d8990f"), "Name1" : "Sam", "Name" : "Bob", "Age" : 26 }
以下是从MongoDB的另一列中设置相似名称的查询-
> db.demo51.find().forEach( function (d) { ... d.Name1 = d.Name; ... db.demo51.save(d); ... });
在find()
方法的帮助下显示集合中的所有文档-
> db.demo51.find();
这将产生以下输出-
{ "_id" : ObjectId("5e27108ccfb11e5c34d8990d"), "Name1" : "David", "Name" : "David", "Age" : 24 } { "_id" : ObjectId("5e27108dcfb11e5c34d8990e"), "Name1" : "Mike", "Name" : "Mike", "Age" : 22 } { "_id" : ObjectId("5e27108ecfb11e5c34d8990f"), "Name1" : "Bob", "Name" : "Bob", "Age" : 26 }