当前位置: 移动技术网 > IT编程>数据库>MongoDB > Mongodb 利用mongoshell进行数据类型转换的实现方法

Mongodb 利用mongoshell进行数据类型转换的实现方法

2018年01月25日  | 移动技术网IT编程  | 我要评论

$type操作符

检测类型

种类 代号 别名

double 1 “double”
string 2 “string”
object 3 “object”
array 4 “array”
binary data 5 “bindata”
undefined 6 “undefined” deprecated.
objectid 7 “objectid”
boolean 8 “bool”
date 9 “date”
null 10 “null”
regular expression 11 “regex”
dbpointer 12 “dbpointer”
javascript 13 “javascript”
symbol 14 “symbol”
javascript (with scope) 15 “javascriptwithscope”
32-bit integer 16 “int”
timestamp 17 “timestamp”
64-bit integer 18 “long”
min key -1 “minkey”
max key 127 “maxkey

db.article.find({data:{$type:2}) //寻找data字段为string的文档

foreach函数

对查询结果集合中每个文档使用js函数

cursor.foreach(function)
iterates the cursor to apply a javascript function to each document from the cursor.

使用例子

将data.taglist数组中的string转换为int32,x代表迭代传入的文档

db.article.find({"data.taglist.0":{$type:2}}).foreach(function(x){
var i=0;
var length=x.data.taglist.length; 
for(i=0;i<length;i++ ){ 
 if(typeof x.data.taglist[i] === 'string') {
  x.data.taglist[i]=numberint(x.data.taglist[i]); 
 } 
};
db.article.save(x)})

note

1.使用js新特性要注意,比如我的是不支持for(var a of b)的,还有注意string是小写啊

2.可以使用print输出

db.users.find().foreach( function(mydoc) { print( "user: " + mydoc.name ); } );

以上这篇mongodb 利用mongoshell进行数据类型转换就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网