1

I have a Mongo Document that contains a large list of primitive ints. Using the Java MongoDB API, I can store the int[] directly, for example:

DBCollection coll = test.getCollection("test");
int[] myInts = {3,4,5,56};
DBObject doc = new BasicDBObject("arr", myInts);
coll.insert(doc);

But when I retrieve the data, I get back a BasicDBList that contains Integer objects:

DBCollection coll = test.getCollection("test");
DBObject obj = coll.findOne();
BasicDBList list =(BasicDBList)obj.get("arr");

Is there a way of getting this data in the same form that I inserted it (int[])? Because the arrays are going to be very large, I don't want an Integer object created for every array element.

3
  • Autoboxing makes it pretty transparent. What's the problem? Commented Oct 17, 2013 at 21:36
  • I realize that from a coding point of view, there's no problem. The problem is that I am dealing with large amounts of data, and I don't want the memory and processing overhead of creating Integer objects, when my application only requires ints. Commented Oct 17, 2013 at 21:56
  • Do you know what the overhead for doing this is? Commented Oct 17, 2013 at 22:14

1 Answer 1

0

Generally - no. You are going to get a List back.

You can try saving the array as a binary blob but then you will lose the ability to query that array and you will have to encode/decode the bytes to/from the array of integers.

There is some overhead in transforming the integer value into Integer objects but that overhead is limited by the JVM maintaining a cache of the Integer values from -128 to 127. (You have some control with the -XX:AutoBoxCacheMax for oracle JVMs). The (array) list itself will have minimal overhead compared to an array of int.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, that's interesting - I think my worry was because I've had trouble when dealing with large arrays of Doubles, and I thought the same would be true of Integers.
Just wanted to check - the range you specified is for bytes. I'm wondering if the caching works for larger ranges too (shorts and ints). I will check out that JVM option.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.