MongoDb将ObjectId类型转String类型。

其中:test 是collection名称

将ObjectId类型转为String类型,复制为新记录:

db.test.find({"_id":{$type:7}}).forEach(
  function(doc){
      //doc._id=doc._id.toString();
      //doc._id=String(doc._id);
      doc._id=doc._id.valueOf();
      db.test.save(doc);
  }
);

主键是ObjectId类型,转为String类型:

db.test.find({_id:{$type:"objectId"}}).forEach(function(doc){
  var oldid = doc._id;
  doc._id = doc._id.valueOf();
  db.test.insert(doc);
  db.test.remove({_id: oldid});
});

 

对照表

Type		 Number	    Alias		    Notes
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 Expression11    "regex"	
DBPointer	   12       "dbPointer"    	 Deprecated.
JavaScript     13	    "javascript"	
Symbol		   14       "symbol"    	 Deprecated.
JavaScript(with scope)15"javascriptWithScope"	
32-bit integer 16	    "int"	
Timestamp	   17	    "timestamp"	
64-bit integer 18	    "long"	
Decimal128	   19	    "decimal"     	 New in version 3.4.
Min key		   -1	    "minKey"	
Max key		   127	    "maxKey"

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐