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

Thay đổi kiểu dữ liệu trường trong MongoDB

Ví dụ chuyển kiểu String sang Int. Aggregation không cho phép đổi kiểu trực tiếp, cần viết script.

Tạo collection changeDataType:

>db.changeDataType.insertOne({"StudentName":"Larry","StudentAge":23,"StudentZipCode":"10001","isProgrammer":false});
{ "acknowledged" : true, "insertedId" : ObjectId("5c6ed4976fd07954a4890694") }

Kiểm tra kiểu dữ liệu các trường:

> checkType=db.changeDataType.findOne();
> typeof checkType._id; // object
> typeof checkType.StudentName; // string
> typeof checkType.StudentAge; // number
> typeof checkType.StudentZipCode; // string
> typeof checkType.isProgrammer; // boolean

Chuyển StudentZipCode từ string sang number:

> db.changeDataType.find().forEach(function(ch) { db.changeDataType.update({"_id":ch._id}, {"$set": {"StudentZipCode":parseInt(ch.StudentZipCode)}}); });

Kiểm tra lại:

> againCheckType=db.changeDataType.findOne();
> typeof againCheckType.StudentZipCode; // number

Trường StudentZipCode đã chuyển từ String sang Number.