Conversion from String to MongoDB ObjectID

泄露秘密 提交于 2020-01-11 10:14:13

问题


I tried converting my String ID to MongoDB ObjectID

public class relevancy_test extends  Object implements Comparable<ObjectId> {
    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<ObjectId, DBObject> updateMap = new HashMap<ObjectId, DBObject>();
        List<DBObject> 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);
        }
    }
}

Here (String) postObj.get("_id") is of form "8001_469437317594492928_1400737805000"

On running following error shows up

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

回答1:


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)




回答2:


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



回答3:


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.




回答4:


While retrieving from List cast it directly to ObjectId

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



回答5:


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
    }


来源:https://stackoverflow.com/questions/29553845/conversion-from-string-to-mongodb-objectid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!