Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Ngẫu nhiên hóa dữ liệu duy nhất MongoDB: tạo email bắt đầu bằng "John"

Để ngẫu nhiên hóa dữ liệu duy nhất, sử dụng Math.random() trong MongoDB shell.

Tạo collection với EmailId null:

> db.demo561.insertOne({EmailId:null});
{ "acknowledged" : true, "insertedId" : ObjectId("5e8f490454b4472ed3e8e86c") }
> db.demo561.insertOne({EmailId:null});
{ "acknowledged" : true, "insertedId" : ObjectId("5e8f490654b4472ed3e8e86d") }
> db.demo561.insertOne({EmailId:null});
{ "acknowledged" : true, "insertedId" : ObjectId("5e8f490a54b4472ed3e8e86e") }

Hiển thị ban đầu:

> db.demo561.find();

Sử dụng forEach duyệt cursor, cập nhật từng tài liệu với email ngẫu nhiên bắt đầu bằng "John":

> db.demo561.find().forEach(function(doc){
...     db.demo561.update({_id : doc._id}, {$set:{
...         EmailId:'John'+Math.random()*100000000000000000+'@'+Math.random()*100000000000000000+'.com'
...     }})
... })

Kiểm tra kết quả (email duy nhất ngẫu nhiên):

> db.demo561.find();
{ "_id" : ObjectId("5e8f490454b4472ed3e8e86c"), "EmailId" : "John23607829153155868@62688631475897960.com" }
{ "_id" : ObjectId("5e8f490654b4472ed3e8e86d"), "EmailId" : "John63351292234094710@79460595429439740.com" }
{ "_id" : ObjectId("5e8f490a54b4472ed3e8e86e"), "EmailId" : "John71315584787457890@99884571221675000.com" }