Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB storing arrays of ObjectId's

In my database I have to store an array of object ids. What should I use? Something like this:

[ObjectId("50350e12a36feb1be6000364"), ObjectId("57350e12a37fef1be6000922"), ObjectId("10350e17d34ffb1be6200925")]

or something like this:

["50350e12a36feb1be6000364", "57350e12a37fef1be6000922", "10350e17d34ffb1be6200925"]

I could save space with the second, and then cast to ObjectId, but am I loosing anything by using this approach? Do ObjectIds behave like foreign keys in relational databases?

like image 283
Francisco Costa Avatar asked Sep 17 '12 18:09

Francisco Costa


People also ask

Can MongoDB store arrays?

One of the benefits of MongoDB's rich schema model is the ability to store arrays as document field values. Storing arrays as field values allows you to model one-to-many or many-to-many relationships in a single document, instead of across separate collections as you might in a relational database.

How do I add an array of strings in MongoDB?

ArrayList<String> stringArray = new ArrayList<String>(); BasicDBObject document = new BasicDBObject(); document. put("master", stringArray); db. getCollection("master"). insert(document);

How do I query an array of objects in MongoDB?

To search the array of object in MongoDB, you can use $elemMatch operator. This operator allows us to search for more than one component from an array object.


2 Answers

I would definitely go with the first approach, storing the ObjectIds directly. This saves space, as ObjectId is 12 bytes whereas the second approach string is 24 bytes.

Also, if the ObjectIds are used to fetch the objects later, storing as ObjectId saves some hassle.

like image 126
jhonkola Avatar answered Oct 09 '22 03:10

jhonkola


Unless you have a good reason not to, store them as an array of ObjectIds. It's more compact (12 bytes vs. 24) and it more accurately reflects what's stored. It can also enable driver-level support for following ObjectId references.

like image 42
JohnnyHK Avatar answered Oct 09 '22 01:10

JohnnyHK