Conversion from String to MongoDB ObjectID

与世无争的帅哥 提交于 2019-12-01 22:38:42

As I see there are two issue here:

  1. How to get proper id of ObjectID instance?

The value 8001_469437317594492928_1400737805000 is not a HEX value which you can see in the DB but an explicit concatenation of time, machine id, pid and counter components. This components are used to generate HEX value. To get HEX value you need to use method ToString of your ObjectID instance.

Reference to explanation of ObjectID components here: http://api.mongodb.com/java/current/org/bson/types/ObjectId.html

  1. How to create ObjectId instance with specific Id

In order to create new ObjectID instance with specific HEX value use this: var objectId = new ObjectId(hexStringId)

Here is an example that will serve you:

public List<Persona> findAlls() {
        List<Persona> personas = new ArrayList();
        MongoCollection<BasicDBObject> collection = baseDato.database.getCollection("persona", BasicDBObject.class);
        try (MongoCursor<BasicDBObject> 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 is a 12-byte BSON type

Here your string "8001_469437317594492928_1400737805000" is not 12 byte BSON type. so update according to ObjectId

To generate a new ObjectId using the ObjectId() constructor with a unique hexadecimal string:

var stringObjectId = ObjectId("507f191e810c19729de860ea");

Please make string correct to convert string to objectId.

While retrieving from List cast it directly to ObjectId

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

I am able to convert String to ObjectId like below:

Here I am updating zip code of 'address' collection, suppose you will get REST api input like below:

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

Now I have to find address record based on the above mentioned id (which is an ObjectId in mongodb). I have a mongorepository for that, and using below code to find the the Address record:

@Repository
public interface AddressRepository extends MongoRepository<Address, String>{

@Query("{'_id': ?0}")
Address findByObjectId(ObjectId id);

}

And use this repository method in your service class, like:

    public void updateZipCode(Address addressInput){
        Address address = 
addressRepository.findByObjectId(new ObjectId(addressInput.getId()));
        //here you will get address record based on the id
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!