从String转换为MongoDB ObjectID

我尝试将我的String ID转换为MongoDB ObjectID

public class relevancy_test extends Object implements Comparable { public static void main(String[] args) throws UnknownHostException { MongoClient mongo = new MongoClient("localhost", 27017); DB mydb = mongo.getDB("test"); DBCollection mycoll = mydb.getCollection("mytempcoll"); BasicDBObject query = null; Map updateMap = new HashMap(); List dbobj = null; DBCursor cursor = mycoll.find(); dbobj = cursor.toArray(); for (DBObject postObj : dbobj) { String id = postObj.get("_id").toString(); ObjectId objId = new ObjectId((String) postObj.get("_id")); updateMap.put(objId, postObj); } } } 

这里(String) postObj.get("_id")的格式为"8001_469437317594492928_1400737805000"

出现运行跟随错误时出现

 Exception in thread "main" java.lang.IllegalArgumentException: invalid ObjectId [8001_469437317594492928_1400737805000] at org.bson.types.ObjectId.(ObjectId.java:181) at org.bson.types.ObjectId.(ObjectId.java:167) at fetch_data_tanmay.relevancy_test.main(relevancy_test.java:48) 

我看到这里有两个问题:

  1. 如何获取ObjectID实例的正确ID?

8001_469437317594492928_1400737805000不是您可以在DB中看到的HEX值,而是时间,机器ID,pid和计数器组件的显式串联。 该组件用于生成HEX值。 要获得HEX值,您需要使用ObjectID实例的方法ToString。

此处参考ObjectID组件的说明: http : //api.mongodb.com/java/current/org/bson/types/ObjectId.html

  1. 如何使用特定Id创建ObjectId实例

为了创建具有特定HEX值的新ObjectID实例,请使用以下命令: var objectId = new ObjectId(hexStringId)

这是一个为您服务的示例:

 public List findAlls() { List personas = new ArrayList(); MongoCollection collection = baseDato.database.getCollection("persona", BasicDBObject.class); try (MongoCursor cursor = collection.find().iterator()) { while (cursor.hasNext()) { BasicDBObject theObj = cursor.next(); String _id = ((ObjectId) theObj.get("_id")).toHexString(); String nombre = (String) theObj.get("nombre"); String apellido = (String) theObj.get("apellido"); String usuario = (String) theObj.get("usuario"); String contrasenna = (String) theObj.get("contrasenna"); Persona persona = new Persona(); persona.setNombre(nombre); persona.setApellido(apellido); persona.setUsuario(usuario); persona.setContrasenna(contrasenna); personas.add(persona); } } return personas; } 

ObjectId是12字节的BSON类型

这里您的字符串“8001_469437317594492928_1400737805000”不是12字节BSON类型。 所以根据ObjectId更新

要使用带有唯一hex字符串的ObjectId()构造函数生成新的ObjectId:

 var stringObjectId = ObjectId("507f191e810c19729de860ea"); 

请将字符串更正为将字符串转换为objectId。

从List中检索时将其直接转换为ObjectId

  for (DBObject postObj : dbobj) { ObjectId objId = (ObjectId)postObj.get("_id"); updateMap.put(objId, postObj); } 

我能够将String转换为ObjectId,如下所示:

这里我正在更新’address’集合的邮政编码,假设您将获得如下所示的REST api输入

 { "id": "5b38a95eb96e09a310a21778", "zip":"10012" } 

现在我必须根据上面提到的id(mongodb中的ObjectId)找到地址记录。 我有一个mongorepository ,并使用下面的代码来查找地址记录:

 @Repository public interface AddressRepository extends MongoRepository{ @Query("{'_id': ?0}") Address findByObjectId(ObjectId id); } 

并在服务类中使用此存储库方法,如:

  public void updateZipCode(Address addressInput){ Address address = addressRepository.findByObjectId(new ObjectId(addressInput.getId())); //here you will get address record based on the id }