I'm totally lost on doing CRUD and other operations on array elements in an embedded Array in mongodb using c# drivers.
given I have the following classes (simple example):
public class Child
{
public ObjectId Id;
public DateTime dateOfBirth;
public string givenName;
}
class Family
{
public ObjectId Id;
public string name;
public List<Child> children;
}
My collection should store Family documents.
How do I:
- Add a new child to a Family
- Delete a certain child
- Update one Child
- Count the children of one family
- get the youngest child of a family
- Load one specific Child
WITHOUT loading the whole Family object
Although I'm taking part in a mongo university class mongo.net I'm completely lost and the documentation on working with arrays is almost not existing.
I know got answers for 1-4:
//Add child
families.UpdateOne(Builders<Family>.Filter.Where(x=>x.name=="Burkhart"), Builders<Family>.Update.AddToSet("children",
new Child() {dateOfBirth = new DateTime(2005, 4, 26), givenName = "Finn"}));
// Add another
families.UpdateOne(Builders<Family>.Filter.Where(x => x.name == "Burkhart"), Builders<Family>.Update.AddToSet("children",
new Child() { dateOfBirth = new DateTime(2007, 4, 26), givenName = "Florentina" }));
//remove one
families.UpdateOne(Builders<Family>.Filter.Where(x => x.name == "Burkhart"),
Builders<Family>.Update.PullFilter(c => c.children, m => m.givenName == "Florentina"));
//update one
families.UpdateOne(Builders<Family>.Filter.Where(x => x.name == "Burkhart" && x.children.Any(c => c.givenName =="Finn")),
Builders<Family>.Update.Set(x=> x.children[-1].givenName,"Finn Linus"));
//count children
var numberOfChildren =
families.Aggregate()
.Match(f => f.name == "Burkhart")
.Project(new BsonDocument("count", new BsonDocument("$size", "$children")))
.FirstOrDefault()
.GetValue("count")
.ToInt32();