What is the best practice to "join" a bunch of values ​​in a mongoose / mongoob without a population

Let me start by stating that I know about the filling method that mongoose offers, but since my work decided to switch to the native mongodb drivers in the future, I can no longer rely on filling to avoid working on the latter from above.

If I have two collections of documents

People {_id:1, name:Austin} {_id:2, name:Doug} {_id:3, name:Nick} {_id:4, name:Austin} Hobbies: {Person: 1, Hobby: Cars} {Person:1, Hobby: Boats} {Person:3, Hobby: Chess} {Person:4, Hobby: Cars} 

How should I join each document with people with Hobbies. Ideally, I would prefer to only call the database twice to get people, and a second time to get a hobby, and then return to the client application objects that they joined.

+6
source share
1 answer

It depends on your main concern. In general, I would say to include hobbies in People, for example:

 { "_id":1, "name":"Austin", "hobbies": [ "Cars","Boats" ] }, { "_id":2, "name":"Doug", "hobbies": [] }, { "_id":3, "name":"Nick", "hobbies": [ "Chess" ] }, { "_id":4, "name":"Austin", "hobbies": [ "Cars" ] } 

which will give you the opportunity to use an index with several keys on hobbies and allow such requests:

 db.daCollection.find({"hobbies":"Cars"}) 

which will return both Austins as complete documents. Yes, I know there will be a lot of redundant entries. If you try to prevent this, model it as follows:

 { "_id": 1, "name":"Cars" },... { "_id":1, "name":"Austin", "hobbies": [ 1, ... ] } 

why an additional index is needed in the hobby name field. Therefore, when you want to find every person who is in the cars, you need to find _id and request it as

 db.person.find({"hobbies":1}) 

I think this is simpler, more intuitive and faster for most use cases if you use an attachment.

+1
source

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


All Articles