更改String类型为Date类型
db.getCollection('bond_sentiment_bulletin').find({'pubDate': {$type:2}}).forEach(
function(doc){
db.getCollection('bond_sentiment_bulletin').update({'_id': doc._id},{$set:{'pubDate': new ISODate(doc.pubDate)}})
}
)
or
db.getCollection('bond_sentiment_bulletin').find({'pubDate': {$type:2}}).forEach(
function(doc){
doc.pubDate = new ISODate(doc.pubDate);
db.getCollection('bond_sentiment_bulletin').save(doc);
}
)
更改Date类型为String类型
db.getCollection('bond_sentiment_bulletin').find({"_id" : 416,'pubDate':{$type:9}}).forEach(
function(x){
x.pubDate = x.pubDate.toISOString();
db.getCollection('bond_sentiment_bulletin').save(x);
}
)
将类型转为str
db.getCollection('bond_sentiment_bulletin').find({"_id" : 419}).forEach(
function(x){
x.status = String(x.status);
db.getCollection('bond_sentiment_bulletin').save(x);
}
)
截取字符串长度
db.getCollection('bond_sentiment_bulletin').find({"_id" : 416,'pubDate':{$type:2}}).forEach(
function(x){
x.pubDate = x.pubDate.substr(0,10);
db.getCollection('bond_sentiment_bulletin').save(x);
}
)
更改Date类型为String类型,并截取字符串长度
db.getCollection('bond_sentiment_bulletin').find({"_id" : 416,'pubDate':{$type:2}}).forEach(
function(x){
x.pubDate = x.pubDate.toISOString().substr(0,10);
db.getCollection('bond_sentiment_bulletin').save(x);
}
)
把时间类型转为NumberLong的时间戳类型
db.getCollection('bond_sentiment_bulletin').find({"_id" : 419,'pubDate':{$type:9}}).forEach(
function(x){
x.pubDate = NumberLong(x.pubDate.getTime()/1000);
db.getCollection('bond_sentiment_bulletin').save(x);
}
)
设置字段为int类型,NumberInt(3),默认是double类型
db.getCollection('bond_sentiment_bulletin').find({"sentiment" : null}).forEach(
function(item){
db.getCollection('bond_sentiment_bulletin').update({"_id":item._id},{$set:{"sentiment":NumberInt(3)}})
}
)
修改double类型为int类型
db.getCollection('bond_sentiment_bulletin').find({'sentiment' : { $type : 1 }}).forEach(
function(x) {
x.sentiment = NumberInt(x.sentiment);
db.getCollection('bond_sentiment_bulletin').save(x);
}
)
字符串转为浮点数
db.getCollection('bond_sentiment_bulletin').find({'editTime': {$type:2}}).forEach(
function(doc){
db.getCollection('bond_sentiment_bulletin').update({'_id': doc._id},{$set:{'editTime': parseFloat(doc.editTime)}})
}
)
字符串转为double
db.getCollection('bond_sentiment_bulletin').find({'editTime': {$type:2}}).forEach(
function(doc){
db.getCollection('bond_sentiment_bulletin').update({'_id': doc._id},{$set:{'editTime': parseInt(doc.editTime)}})
}
)
instanceof函数,判断某个字段是某个类型
count=0;
db.getCollection('bond_sentiment_bulletin').find({"_id" : 423}).forEach(function(x){if(x.pubDate instanceof Date){count++}});
print(count);
查询address字段数据类型为字符串
db.getCollection('bond_sentiment_bulletin').find({address:{$type:2}}) //查询address字段数据类型为字符串
db.getCollection('bond_sentiment_bulletin').find({address:{$type:"string"}}) //查询address字段数据类型为字符串
查询附件某个字段存在的
db.getCollection('bond_sentiment_bulletin').find({'_id':{$gte:587863,$lte:800000},"isPrimary" : 0,'attach':{$elemMatch:{'UpdateTime': {$exists :true}}}})
MongoDB支持许多数据类型的列表下面给出: