How can I improve this query? Perhaps use aggregation? Help pls

I have a function that is calling my atlas cluster 3 times just to find and update data. I would like to know if I can change the query below perhaps to use Aggregations to make it more succinct? It works , but looks very ameteruish! Help me improve the psudeo code below :slight_smile:

//step 1 - findOne to obtain the results to use in the next stage
const dbResult = await mClient.db().collection(‘quicksend’).findOne({ slug: data.slug })
//step 2
if (!dbResult) {
throw Error(‘No Results’)
}
let fileObjects = dbResult.fileObjects // get the data I need
// Do some external processing on AWS s3 based on the dbResults

//step 3 - Get some userDAta from another collection with a filter from the post body
const userData = await mClient.db().collection(‘users’).findOne({_id: new ObjectId(data.userid)}, {projection : {fullName : 1, company : 1,email:1}})

//step 4
create a new array based on the result of step 3

// step 5 - Finally update the database with the data I need from the previous steps
await mClient.db().collection(‘quicksend’).findOneAndUpdate({ slug: data.slug }, {$set: {senderId : data.userid, senderEmail : userData.email,senderName: userData.fullName,company:userData.company,fileObjects:newFileObjectsPath }})

Above works, but as you can see I am calling the database 3 times. I think I can use lookup, but I need to do some external processing based on the result after step 1.

Is there anything wrong with what I am doing above?

Thanks.

Hi @Rishi_uttam

I think what you’re doing is fine because:

  1. It’s clear from each step what you’re doing
  2. You need a couple of extra information before being able to do the update
  3. The code is very readable

Personally, I don’t think it’s worth “optimizing” the code for the sake of having a single database call. For me personally, a readable code is more valuable. There may be some ways to minimize the database call, but if the resulting code is unreadable, you lose a lot more than just round trip time to the server and back.

Of course this is just my opinion :slight_smile:

Best regards
Kevin

1 Like

kevin thanks so much, appreciate it, so i will leave it.
yes your’re right, i do need some information from the previous call.

For some reason when watching the Mongo 2021 talks, aggregation was all the rage, and if not using aggregation i thought i was doing something out of date and slow. . thanks. oh and i also dont have 1 million customers a second, if i did yes optimization would make sense.

1 Like