如何在 MongoDB 中复制属性?

mongodbdatabasebig data analytics更新于 2026/2/13 4:22:17

要将一个属性的值复制到另一个属性,请使用 $set 和 update() 方法。让我们创建一个包含文档的集合。 −

> db.demo55.insertOne({"ShippingDate":'',"date":new ISODate("2019-01-21")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2716dfcfb11e5c34d89915")
}
> db.demo55.insertOne({"ShippingDate":'',"date":new ISODate("2020-05-12")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2716ebcfb11e5c34d89916")
}

借助 find() 方法显示集合中的所有文档 −

> db.demo55.find();

这将产生以下输出 −

{ "_id" : ObjectId("5e2716dfcfb11e5c34d89915"), "ShippingDate" : "", "date" : ISODate("2019-01-21T00:00:00Z") }
{ "_id" : ObjectId("5e2716ebcfb11e5c34d89916"), "ShippingDate" : "", "date" : ISODate("2020-05-12T00:00:00Z") }

Following is the query to copy attributes in MongoDB −

> db.demo55.find({}).forEach(function(c){
...    db.demo55.update({_id: c._id}, {$set: {ShippingDate:c.date}});
... });

借助 find() 方法显示集合中的所有文档 −

> db.demo55.find();

这将产生以下输出 −

{ "_id" : ObjectId("5e2716dfcfb11e5c34d89915"), "ShippingDate" : ISODate("2019-01-21T00:00:00Z"), "date" : ISODate("2019-01-21T00:00:00Z") }
{ "_id" : ObjectId("5e2716ebcfb11e5c34d89916"), "ShippingDate" : ISODate("2020-05-12T00:00:00Z"), "date" : ISODate("2020-05-12T00:00:00Z") }

相关文章