필드 유형을 변경하려면 어떻게 해야 합니다.
저는 mongo 쉘 안에서 필드의 종류를 바꾸려고 합니다.
나 이거 하고 있어...
db.meta.update(
{'fields.properties.default': { $type : 1 }},
{'fields.properties.default': { $type : 2 }}
)
근데 안 돼!
「 」를 $type데이터의 유형은 올바른 데이터에 대해 업데이트를 수행하는 것입니다.
이 경우, 이 때, 이 때, 이 때, 이 때, 이 때, 이 부분을 것 .$type 1(더블)부터 2(스트링)까지입니다.
DB에서 DB)을 합니다.new String(x)츠키다
해야 할 를 할 수 .find(...).forEach(function(x) {})구문을 사용합니다.
아래의 두 번째 코멘트에 대한 답변입니다.를 변경합니다.bad 내의 foo.
db.foo.find( { 'bad' : { $type : 1 } } ).forEach( function (x) {
x.bad = new String(x.bad); // convert field to string
db.foo.save(x);
});
문자열 필드를 정수로 변환:
db.db-name.find({field-name: {$exists: true}}).forEach(function(obj) {
obj.field-name = new NumberInt(obj.field-name);
db.db-name.save(obj);
});
정수 필드를 문자열로 변환:
db.db-name.find({field-name: {$exists: true}}).forEach(function(obj) {
obj.field-name = "" + obj.field-name;
db.db-name.save(obj);
});
★★★★★Mongo 4.2는 집약 파이프라인을 받아들일 수 있으며, 최종적으로 자체 값에 따라 필드를 갱신할 수 있습니다.
// { a: "45", b: "x" }
// { a: 53, b: "y" }
db.collection.updateMany(
{ a : { $type: 1 } },
[{ $set: { a: { $toString: "$a" } } }]
)
// { a: "45", b: "x" }
// { a: "53", b: "y" }
은요.
{ a : { $type: 1 } }일치 쿼리입니다.- 업데이트할 문서를 필터링합니다.
- 「 」를 하고 싶기 에, 「 」는 「 」
"a"때을 하려면 , 은 2배일 때, 2배일 때, 2배일 때, 은 2배일 때 스트링하는 입니다."a"은 「」입니다.1( 중 ( ) - 다음 표에 다양한 유형을 나타내는 코드를 나타냅니다.
파트, 두 번째 파트입니다.
[{ $set: { a: { $toString: "$a" } } }]파이프라인입니다.- 이 업데이트 쿼리가 집약 파이프라인을 사용함을 나타내는 각 괄호에 주의하십시오.
$set는 새로운 집약 연산자입니다(Mongo 4.2이 경우 필드를 변경합니다.- 이것은 간단히 말해 다음과 같이 해석할 수 있다.
"$set"의 의 값"a"로로 합니다."$a"된 ★★★★"$toString". - 여기서 정말 새로운 것은 이 모든 것을
Mongo 4.2때 은 갱신할 수 없습니다."a"기존 가치를 기반으로 합니다."$a". - 또, 에 도입된 새로운 집약 연산자를 적어 둡니다.
Mongo 4.0.
더블에서 스트링으로 않은 에는 에 된 다른 중에서 할 수 .Mongo 4.0예를 들면, ..., 등
자신이 로 하는할 수 .{ $toString: "$a" } a $convert ★★★★★★{ $convert: { input: "$a", to: 2 } }서 「」의 값을 지정합니다.to는 다음 표에 기재되어 있습니다.
db.collection.updateMany(
{ a : { $type: 1 } },
[{ $set: { a: { $convert: { input: "$a", to: 2 } } } }]
)
문자열에서 int로의 변환.
db.my_collection.find().forEach( function(obj) {
obj.my_value= new NumberInt(obj.my_value);
db.my_collection.save(obj);
});
문자열에서 이중 변환으로.
obj.my_value= parseInt(obj.my_value, 10);
플로트의 경우:
obj.my_value= parseFloat(obj.my_value);
db.coll.find().forEach(function(data) {
db.coll.update({_id:data._id},{$set:{myfield:parseInt(data.myfield)}});
})
지금까지의 모든 응답은 일부 버전의 forEach를 사용하여 모든 수집 요소 클라이언트 측에서 반복합니다.
단, 다음과 같이 집약 파이프라인과 $out 단계를 사용하여 MongoDB의 서버 측 처리를 사용할 수 있습니다.
$out 단계는 기존 컬렉션을 새로운 결과 컬렉션으로 아토믹하게 대체합니다.
예:
db.documents.aggregate([
{
$project: {
_id: 1,
numberField: { $substr: ['$numberField', 0, -1] },
otherField: 1,
differentField: 1,
anotherfield: 1,
needolistAllFieldsHere: 1
},
},
{
$out: 'documents',
},
]);
문자열 유형의 필드를 날짜 필드로 변환하려면 메서드를 사용하여 메서드에서 반환된 커서를 반복하고 루프 내에서 필드를 날짜 개체로 변환한 다음 연산자를 사용하여 필드를 업데이트해야 합니다.
일괄 업데이트에 Bulk API를 사용하면 예를 들어 1000개의 요구 중 1개만 서버에 모든 요청을 보내는 것이 아니기 때문에 더 나은 성능을 얻을 수 있습니다.
은 이 방법을 번째 할 수 있는 벌크 API를 .첫 번째 예에서는 MongoDB 버전에서 사용할 수 있는 벌크 API를 사용합니다.>= 2.6 and < 3.2를 .를하여 업데이트합니다.created_at필 - 짜드 :
var bulk = db.collection.initializeUnorderedBulkOp(),
counter = 0;
db.collection.find({"created_at": {"$exists": true, "$type": 2 }}).forEach(function (doc) {
var newDate = new Date(doc.created_at);
bulk.find({ "_id": doc._id }).updateOne({
"$set": { "created_at": newDate}
});
counter++;
if (counter % 1000 == 0) {
bulk.execute(); // Execute per 1000 operations and re-initialize every 1000 update statements
bulk = db.collection.initializeUnorderedBulkOp();
}
})
// Clean up remaining operations in queue
if (counter % 1000 != 0) { bulk.execute(); }
버전이다.MongoDB 됩니다.3.2이후 Bulk API를 폐지하고 다음 명령을 사용하여 새로운 apis 세트를 제공하고 있습니다.
var bulkOps = [];
db.collection.find({"created_at": {"$exists": true, "$type": 2 }}).forEach(function (doc) {
var newDate = new Date(doc.created_at);
bulkOps.push(
{
"updateOne": {
"filter": { "_id": doc._id } ,
"update": { "$set": { "created_at": newDate } }
}
}
);
})
db.collection.bulkWrite(bulkOps, { "ordered": true });
배열을 작성하지 않고 int32를 mongo 문자열로 변환하려면 "를 번호에 추가합니다:-)
db.foo.find( { 'mynum' : { $type : 16 } } ).forEach( function (x) {
x.mynum = x.mynum + ""; // convert int32 to string
db.foo.save(x);
});
MondoDB의 오브젝트 타입을 변경하는 데 정말 도움이 된 것은 아마 앞에서 언급했던 단순한 행이었습니다.:
db.Users.find({age: {$exists: true}}).forEach(function(obj) {
obj.age = new NumberInt(obj.age);
db.Users.save(obj);
});
사용자는 내 컬렉션이고 age는 정수(int32)가 아닌 문자열을 가진 객체입니다.
You can easily convert the string data type to numerical data type.
Don't forget to change collectionName & FieldName.
for ex : CollectionNmae : Users & FieldName : Contactno.
이 쿼리를 사용해 보십시오.
db.collectionName.find().forEach( function (x) {
x.FieldName = parseInt(x.FieldName);
db.collectionName.save(x);
});
컬렉션에서 여러 필드의 데이터 유형을 변경해야 하므로 문서 컬렉션에서 여러 데이터 유형을 변경하기 위해 다음을 사용했습니다.오래된 질문에 대답하지만 다른 사람에게 도움이 될 수 있습니다.
db.mycoll.find().forEach(function(obj) {
if (obj.hasOwnProperty('phone')) {
obj.phone = "" + obj.phone; // int or longint to string
}
if (obj.hasOwnProperty('field-name')) {
obj.field-name = new NumberInt(obj.field-name); //string to integer
}
if (obj.hasOwnProperty('cdate')) {
obj.cdate = new ISODate(obj.cdate); //string to Date
}
db.mycoll.save(obj);
});
데모 mongoose를 사용하여 mid 필드 유형을 문자열에서 mongo objectId로 변경
Post.find({}, {mid: 1,_id:1}).exec(function (err, doc) {
doc.map((item, key) => {
Post.findByIdAndUpdate({_id:item._id},{$set:{mid: mongoose.Types.ObjectId(item.mid)}}).exec((err,res)=>{
if(err) throw err;
reply(res);
});
});
});
Mongo ObjectId는 다음과 같은 스타일의 또 다른 예입니다.
답이 다른 사람에게 도움이 되기를 바라는 숫자, 문자열, 부울.
mongodb 콘솔에서 이 스크립트를 사용하여 변환을 플로트하기 위한 문자열로 사용합니다.
db.documents.find({ 'fwtweaeeba' : {$exists : true}}).forEach( function(obj) {
obj.fwtweaeeba = parseFloat( obj.fwtweaeeba );
db.documents.save(obj); } );
db.documents.find({ 'versions.0.content.fwtweaeeba' : {$exists : true}}).forEach( function(obj) {
obj.versions[0].content.fwtweaeeba = parseFloat( obj.versions[0].content.fwtweaeeba );
db.documents.save(obj); } );
db.documents.find({ 'versions.1.content.fwtweaeeba' : {$exists : true}}).forEach( function(obj) {
obj.versions[1].content.fwtweaeeba = parseFloat( obj.versions[1].content.fwtweaeeba );
db.documents.save(obj); } );
db.documents.find({ 'versions.2.content.fwtweaeeba' : {$exists : true}}).forEach( function(obj) {
obj.versions[2].content.fwtweaeeba = parseFloat( obj.versions[2].content.fwtweaeeba );
db.documents.save(obj); } );
그리고 이것은 php)에 있습니다).
foreach($db->documents->find(array("type" => "chair")) as $document){
$db->documents->update(
array('_id' => $document[_id]),
array(
'$set' => array(
'versions.0.content.axdducvoxb' => (float)$document['versions'][0]['content']['axdducvoxb'],
'versions.1.content.axdducvoxb' => (float)$document['versions'][1]['content']['axdducvoxb'],
'versions.2.content.axdducvoxb' => (float)$document['versions'][2]['content']['axdducvoxb'],
'axdducvoxb' => (float)$document['axdducvoxb']
)
),
array('$multi' => true)
);
}
위의 답변은 거의 효과가 있었지만 몇 가지 과제가 있었습니다.
1: 제 1 1:db.collection.save5.xMongoDB 5.x에서는 하지 않게 .
이걸 위해서replaceOne().
문제 2:new String(x.bad)기하급수적인 숫자를 주고 있었다.
나는 사용했다"" + x.bad상기와 같이
내 버전:
let count = 0;
db.user
.find({
custID: {$type: 1},
})
.forEach(function (record) {
count++;
const actualValue = record.custID;
record.custID = "" + record.custID;
console.log(`${count}. Updating User(id:${record._id}) from old id [${actualValue}](${typeof actualValue}) to [${record.custID}](${typeof record.custID})`)
db.user.replaceOne({_id: record._id}, record);
});
수백만 건의 기록을 위해 (향후 조사/참고를 위해) 다음과 같은 결과를 제공합니다.
언급URL : https://stackoverflow.com/questions/4973095/how-to-change-the-type-of-a-field
'programing' 카테고리의 다른 글
| Oracle에서 테이블 잘라내기 오류 발생 (0) | 2023.02.28 |
|---|---|
| HTML을 WordPress Woocommerce 단일 제품 페이지에 통합하는 방법 (0) | 2023.02.28 |
| ASP에서 JSON 개체를 반환하는 중입니다.NET 페이지 (0) | 2023.02.28 |
| AngularJS: 모델 요소가 모델 배열에서 스플라이스된 경우 ng-repeat 목록이 업데이트되지 않음 (0) | 2023.02.28 |
| 내 HTML에서 WordPress 연락처 양식 7을 사용하는 방법 (0) | 2023.02.28 |
