MongoDB query (Using Edge Collection the most efficient way?)

I wrote a collection of users, clubs and followers for the example below. I want to find all user documents from the Users collection that follow the "Famous Club". How can I find them? and which way is the fastest?

More on ' What I Want to Do - Edge Collections

User collection

{ "_id": "1", "fullname": "Jared", "country": "USA" } 

Club Collection

 { "_id": "12", "name": "A famous club" } 

Followers collection

 { "_id": "159", "user_id": "1", "club_id": "12" } 

PS: I can get documents using Mongoose as shown below. However, creating an followers array takes about 8 seconds with 150,000 entries. And the second find query, which is queried using an array of followers, takes about 40 seconds . This is normal?

 Clubs.find( { club_id: "12" }, '-_id user_id', // select only one field to better perf. function(err, docs){ var followers = []; docs.forEach(function(item){ followers.push(item.user_id) }) Users.find( { _id:{ $in: followers } }, function(error, users) { console.log(users) // RESULTS }) }) 
0
mongodb mongoose
source share
1 answer

There is no suitable formula for manipulating many-to-many relationships in MongoDB. Therefore, I combined the collections as inline documents, as shown below. But the most important indexes are created in this case. For example, if you want to request the followingClubs , you should create an index, such as schema.index({ 'followingClubs._id':1 }) , using Mongoose. And if you want to query country and followingClubs , you have to create another index, for example schema.index({ 'country':1, 'followingClubs._id':1 })

Pay attention when working with embedded documents: http://askasya.com/post/largeembeddedarrays

Then you can quickly get your documents. I tried to get the score of 150,000 records using this method, it took only 1 second. This is enough for me ...

ps: we do not forget that in my tests, my Users collection never experienced data fragmentation. Therefore, my queries can demonstrate good performance. Especially, the followingClubs array of embedded documents.

User collection

 { "_id": "1", "fullname": "Jared", "country": "USA", "followingClubs": [ {"_id": "12"} ] } 

Club Collection

 { "_id": "12", "name": "A famous club" } 
0
source share

All Articles