DB/MongoDB
mongodb - 콜렉션 필드 형변환 (How to change the type of a field)
linuxism
2013. 10. 7. 00:38
There is a question already in Stackoverflow, very similar with my question. The thing is that the answer for that questions was for a Java Driver, I am trying to do it in the shell.
I am doing this...
db.meta.update({'fields.properties.default': { $type : 1 }}, {'fields.properties.default': { $type : 2 }})
This is not working!
Answers
The only way to change the $type of the data is to perform an update on the data where the data has the correct type. In this case, it looks like you're trying to change the $type from 1 (double) to 2 (string).http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24type So simply load the document from the DB, perform the cast (new String(x)) and then save the document again. If you need to do this programmatically and entirely from the shell, you can use thefind(...).forEach(function(x) {}) syntax.
In response to the second comment below. Change the field bad from a number to a string in collectionfoo. db.foo.find( { 'bad' : { $type : 1 } } ).forEach( function (x) {
x.bad = new String(x.bad); // convert field to string
db.foo.save(x);
});
| | answered Feb 11 '11 at 20:21 |
|
| |


| // String to Integer db.db-name.find({field-name : {$exists : true}}).forEach( function(obj) { obj.field-name = new NumberInt(obj.field-name); db.db-name.save(obj); } );
// Integer to String db.db-name.find({field-name : {$exists : true}}).forEach( function(obj) { obj.field-name = ""+obj.field-name; db.db-name.save(obj); } );
| answered Oct 17 '11 at 15:45 |
|
| |
| This is what I used for string to int conversion. db.my_collection.find().forEach( function(obj) {
obj.my_value= parseInt(obj.my_value);
db.my_collection.save(obj);
});
|
출처 - http://stackoverflow.com/questions/4973095/mongodb-how-to-change-the-type-of-a-field
new String(x.bad)creates collection of Strings with 0-index-itemx.badvalue. Variant""+x.bad, described by Simone works as desired - creates String value instead of Int32 – Dao Jul 30 '12 at 16:36