C
C#3y ago
LazyGuard

❔ Is there a way to improve this code Performance ?

have a collection of items that have _id and serialNumbers (an array) fields (and other fields as well but irrelevant for the question). I want to do the following: 0. Check that the newSerialNumber is not used in any document. 1. Filter to find out the item with the given id, lets name it ItemX 2. Get all the items that have the same serialNumbers as ItemX. Let's name them ItemsWithSameSerialNumbersAsItemX 3. For each one of the ItemsWithSameSerialNumbersAsItemX, push the newSerialNumber I am doing it as following:
var itemsWithNewSerialNumber = items.find( x => x.SerialNumbers == newSerialNumber );
if (itemsWithNewSerialNumber.Count > 0) {
// throw exception
}

var itemX = items.findOne( x => x.ItemId == Id );

var itemsWithSameSerialNumbersAsItemX = items.find( x => x.SerialNumbers == itemX.SerialNumbers);

var updateDef = Builders<ItemsDto>.Update;

var updates = new List<UpdateDefinition<ItemDto>>
{
updateDef.Push(x => x.SerialNumbers, newSerialNumber)
}
items.updateMany(
x => x.SerialNumbers,
updates }
)
var itemsWithNewSerialNumber = items.find( x => x.SerialNumbers == newSerialNumber );
if (itemsWithNewSerialNumber.Count > 0) {
// throw exception
}

var itemX = items.findOne( x => x.ItemId == Id );

var itemsWithSameSerialNumbersAsItemX = items.find( x => x.SerialNumbers == itemX.SerialNumbers);

var updateDef = Builders<ItemsDto>.Update;

var updates = new List<UpdateDefinition<ItemDto>>
{
updateDef.Push(x => x.SerialNumbers, newSerialNumber)
}
items.updateMany(
x => x.SerialNumbers,
updates }
)
Here I am making 4 calls to the database (3 finds and 1 update). Is there some way to write this more efficiently ?
3 Replies
ero
ero3y ago
Please don't provide incomplete pseudo code when asking for performance increases Show us the entire context, everything that's needed to test
fasadin
fasadin3y ago
your question is not easy one so, best answer that I can give you is It dependents on many factors which you didn’t mentioned write query but differently. as argument you can use select and let DB handle optimalisation something like (pseudo code) select i.* from items i where i.SerialNumbers in (select x.SerialNumbers from items x where x.id = id)
Accord
Accord3y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.

Did you find this page helpful?