LiteDB icon indicating copy to clipboard operation
LiteDB copied to clipboard

[QUESTION] Collection UpdateMany Example

Open seikosantana opened this issue 2 years ago • 3 comments

It might be common sense but how do we use UpdateMany in fluent syntax?

seikosantana avatar Nov 02 '23 10:11 seikosantana

Same for me, I'm tying to find out a way to update one field of a record with a new value using the UpdateMany for example if i have a record like

public record Item(ObjectId Id, int Value);

and a collection that contains many of these

ILiteCollection<Item> collection = db.GetCollection("MyCollection");

how can i assign to each item's value its successor so if i have

collection.Insert(new(1,1)); //record 1
collection.Insert(new(2,2)); //record 2
collection.Insert(new(3,3)); //record 3
collection.Insert(new(4,4)); //record 4

i want that each record's value is increased by 1 so record 1 will become (1,2) , record 2 will become (2,3) and so on...

something like this doesn't seems to work

collection.UpdateMany(
   x => new(x.Id, x.Value +1),
   x => true
);

as it says (at run time) that new is not allowed in the expression (even if it is valid in an expression) again the with keyboard is not valid in expression at compile time so it is excluded. :(

any idea?

PhotoAtomic avatar Feb 07 '24 13:02 PhotoAtomic

Solved: i've changed record to class so to be able to have setter on properties too

public class Item{
   public ObjectId Id {get; set; }
   public int Value {get; set;}
}

and the update become quite easilly

collection.UpdateMany(
   x => new Item {Value = x.Value +1},
   x => true
);

PhotoAtomic avatar Feb 07 '24 13:02 PhotoAtomic