我想查詢存儲在我的MongoDB中的java.util.UUID,使用與存儲的UUID所基於的字符串相對應的字節[]。MongoDB [Java]:如何以字節[]格式查詢存儲的UUID?
我見過Mongo Driver自動將UUID轉換爲字節並將其存儲爲BinData(子類型)。下面是我用來保存UUID代碼:
UUID originalUUID= UUID.fromString("7ee973c0-54b5-11e4-aaed-0002a5d5c51b");
MongoClient mongoClient = new MongoClient("localhost" , 27017);
DB db = mongoClient.getDB("test");
DBCollection coll = db.getCollection("test");
BasicDBObject query = new BasicDBObject("_id", originalUUID);
coll.save(query);
我知道我們可以很容易地檢索與UUID對象在BasicDBObject值這個文件,但是我想用一個byte []代替。畢竟,它在我的Mongo中必須是字節嗎? 我知道Java在發送給Mongo之前搞亂了字節順序,但是我一直無法使它工作。我的檢索代碼是在這裏:
String stringOne = "7ee973c0-54b5-11e4-aaed-0002a5d5c51b";
// It's the same UUID String
BasicDBObject find = new BasicDBObject("_id", stringOne.getBytes());
DBCursor cursor = null;
cursor = coll.find(find);
while(cursor.hasNext()){
BasicDBObject dbObject = (BasicDBObject)cursor.next();
byte[] received = (byte[])dbObject.get("_id");
System.out.println(new String(received));
}
我也試過小端編碼是這樣的:
byte[] bytes = new byte[16];
ByteBuffer bb = ByteBuffer.wrap(bytes);
bb.order(ByteOrder.LITTLE_ENDIAN);
bb.putLong(originalUUID.getMostSignificantBits());
bb.putLong(originalUUID.getLeastSignificantBits());
BasicDBObject find = new BasicDBObject("_id", bb.array()); //Also tried flipping bb.
這一切都不奏效。有人可以通過解決方案提供一些見解嗎?
謝謝!
你可以得到光標? – 2014-11-14 17:27:38
我不明白。獲得「光標」是什麼意思? – 2014-11-14 17:56:42