Java 从 String 到 MongoDB ObjectID 的转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29553845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 08:12:17  来源:igfitidea点击:

Conversion from String to MongoDB ObjectID

javamongodbmongodb-java

提问by Tanmay Awasthi

I tried converting my String ID to MongoDB ObjectID

我尝试将我的字符串 ID 转换为 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"

(String) postObj.get("_id")是形式"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)

采纳答案by Vadzim Dabravolski

As I see there are two issue here:

正如我所见,这里有两个问题:

  1. How to get proper id of ObjectID instance?
  1. 如何获得 ObjectID 实例的正确 id?

The value 8001_469437317594492928_1400737805000is 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.

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

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

此处引用 ObjectID 组件的说明:https: //api.mongodb.com/java/3.0/org/bson/types/ObjectId.html

  1. How to create ObjectId instance with specific Id
  1. 如何创建具有特定 ID 的 ObjectId 实例

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

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

回答by Dineshaws

ObjectId is a 12-byte BSON type

ObjectId 是一个 12 字节的 BSON 类型

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

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

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

使用带有唯一十六进制字符串的 ObjectId() 构造函数生成新的 ObjectId:

var stringObjectId = ObjectId("507f191e810c19729de860ea");

Please make string correct to convert string to objectId.

请使字符串正确以将字符串转换为 objectId。

回答by rns

While retrieving from List cast it directly to ObjectId

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

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

回答by Carlos Alberto Gonzalez

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

回答by Ashu Phaugat

I am able to convert String to ObjectId like below:

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

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

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

{  
   "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 mongorepositoryfor that, and using below code to find the the Address record:

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

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