Using Binary Data datetype for storing byte arrays in mongoDB

来源:互联网 发布:波士顿动力 知乎 编辑:程序博客网 时间:2024/05/29 01:53

Store GUIDs as BinData, rather than as strings

BSON includes a binary data datatype for storing byte arrays. Using this will make the id values, and their respective keys in the _id index, twice as small.

Note that unlike the BSON Object ID type (see above), most UUIDs do not have a rough ascending order, which creates additional caching needs for their index.

根据官网文档,以byte arrays的方式存储数据,特别是_id,能减少索引大小,提高效率,不过没有验证。目前的Java Driver对此支持好像不是很好,其Binary类可以把数据存入mongodb,但是读取字段时却不能进行强制转换回来。

String t = "123456789abcdef9";

Binary id = new Binary(t.getBytes());

BasicDBObject obj = new BasicDBObject();

obj.append("_id", id).append("name", "me");

coll.insert(obj);
System.out.println(coll.find(obj).explain());

DBCursor cursor = coll.find(obj);

while(cursor.hasNext())

{

DBObject o = cursor.next();

System.out.println(o);

Binary b = (Binary) o.get("_id"); // won't work, will get Exception when doing data type convertion

System.out.println(new String((byte[])o.get("_id"))); // this way works well

// System.out.println(k);

}

原创粉丝点击