Wednesday, 15 March 2017

MongoDB and mongoose performance improvements

I'm looking for design/performance advice for mongodb collections.

I have a doctor schema with few fields like ownerId (user who created the doctor document) , and sharedWith (array of objects containing id and schema name) . Here is a simplified example:

{ 
name: {type: String},
ownerId: {type: ObjectId},
sharedWith: {
     objId: {type: ObjectId},
     objType: {type: String}
}

* objType can be team or user . meaning you can share a doctor with a team of user or a single user.

On the UI I have a list of doctors which should display all of 'my' doctors and shared with me doctors. My doctors would have ownerId equal to my own. And shared with me doctors would be either those that were directly shared with me, or shared with a team I'm on.

Here is the query I run:

db.teams.find({$or: [{members: {"$elemMatch": {obj: myUserId}}}, {createdBy: myUserId}]}, function(err, teams){
     ///extract ids here into teamIds variable
     db.doctors.find({$or: [{sharedWith: {"$elemMatch": {obj: myUserId}}}, {"sharedWith": {"$elemMatch": {obj: {$in: teamIds}}}}]}
}, function(err, doctors){ //handle doctors});

Initially I didn't have any indexes , and so queries became pretty slow as we got more doctors in the system. I then added indexes

db.doctors.createIndex({'sharedWith.obj': 1})
db.doctors.createIndex({'ownerId':1})
db.teams.createIndex({'members.obj': 1})
db.teams.createIndex({'createdBy': 1})

Queries are looking a bit faster now.

Are there any other improvements you could suggest to make this query faster ?



via user1102956

No comments:

Post a Comment