从字符串转换为MongoDB ObjectID [英] Conversion from String to MongoDB ObjectID

查看:686
本文介绍了从字符串转换为MongoDB ObjectID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将String ID转换为MongoDB ObjectID

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

此处(String) postObj.get("_id")的格式为"8001_469437317594492928_1400737805000"

在运行时出现以下错误

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)

推荐答案

我看到这里有两个问题:

As I see there are two issue here:

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

8001_469437317594492928_1400737805000并非在数据库中可以看到的十六进制值,而是时间,机器ID,PID和计数器组成部分的明确串联.该组件用于生成十六进制值.要获取十六进制值,您需要使用ObjectID实例的方法ToString.

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.

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

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

  1. 如何创建具有特定ID的ObjectId实例

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

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

这篇关于从字符串转换为MongoDB ObjectID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆