MongoDB arrays and objects

Suppose I want to keep a list of items for each user (in MongoDB with Mongoose ODM in Node.js) and a later query to find out if the item belongs to the user. For example, I want to save all the favorite colors of each user, and then see if a particular color belongs to a specific user. It seems to me that it is better to store colors as an embedded object inside a user document, rather than an array in a user document. The reason is that it seems more efficient to check if a color exists in an object, since I can simply check if an object property exists:

if(user.colors.yellow){ //true case } else { //false case } 

Compared to an array, where I have to iterate over the entire array to see if any color exists in the array:

 for (var i = 0; i < user.colors.length; i++) { if(user.colors[i] === "yellow"){ //true case } else { //false case } } 

However, from the many examples I've seen on the Internet, it seems that using arrays for this type of thing is pretty common. Am I missing something? What are the pros and cons and the best way to do this?

+6
source share
2 answers

You do not need to use for-loop if the colors are stored as an array. You can simply use indexOf , as in:

 if(user.colors.indexOf("yellow") != -1){ //true case } 

However, it does not matter whether you use an embedded document or an array; it is not like one or the other, which will give a huge advantage in performance.

+2
source

You often see inline arrays used to store this type of information in MongoDB collections, because if you add an index to an array property, it is efficient for querying, and they use natural syntax. In this case, something like the following (assuming a user collection that contains a color array property):

 db.users.find({id: 1, colors: 'yellow'}) 

If you did this with individual color properties, you would have a more inconvenient query like this, and you would have to index each color separately (instead of just colors , as you would above):

 db.users.find({id: 1, 'colors.yellow': true}) 
+1
source

Source: https://habr.com/ru/post/924936/


All Articles