Mongodb 利用mongoshell進行數據類型轉換


$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 ); } );


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM