C#C
C#4y 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:
  1. Check that the newSerialNumber is not used in any document.
  2. Filter to find out the item with the given id, lets name it ItemX
  3. Get all the items that have the same serialNumbers as ItemX. Let's name them ItemsWithSameSerialNumbersAsItemX
  4. 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 }
)


Here I am making 4 calls to the database (3 finds and 1 update). Is there some way to write this more efficiently ?
Was this page helpful?