Conversion from String to MongoDB ObjectID
Asked Answered
C

5

5

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)
Chellean answered 10/4, 2015 at 5:9 Comment(0)
L
12

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: https://api.mongodb.com/java/3.0/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)

Lycian answered 6/10, 2016 at 17:57 Comment(1)
The second solution worked for me. Actually in my Java Spring MVC this statement is written as ObjectId OfflineModId = new ObjectId("<Valid_HEX_value>");Windywindzer
R
1

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;
    }
Retuse answered 30/5, 2017 at 16:7 Comment(0)
L
0

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.

Lava answered 10/4, 2015 at 7:24 Comment(1)
Hey, Could you please guide for #33889444?Swor
S
0

While retrieving from List cast it directly to ObjectId

 for (DBObject postObj : dbobj) {
        ObjectId objId = (ObjectId)postObj.get("_id");
        updateMap.put(objId, postObj);
}
Shoreline answered 11/4, 2015 at 6:51 Comment(0)
G
0

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
    }
Galateah answered 1/7, 2018 at 10:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.