mongodb .net driver V2: How to do array operations -
i'm totally lost on doing crud , other operations on array elements in embedded array in mongodb using c# drivers.
given have 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 i:
- add new child family
- delete child
- update 1 child
- count children of 1 family
- get youngest child of family
- load 1 specific child
without loading whole family object
although i'm taking part in mongo university class mongo.net i'm lost , documentation on working arrays not existing.
i know got answers 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 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 1 families.updateone(builders<family>.filter.where(x => x.name == "burkhart"), builders<family>.update.pullfilter(c => c.children, m => m.givenname == "florentina")); //update 1 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();
as 1-4 fixed - congratulations! please find 5 , 6 discussed in chat.
full code in github repository
var f = generatefaimly(); collection.insertone(f); var sort = bsondocument.parse("{\"kids.dateofbirth\": -1}"); // youngest var project = bsondocument.parse( "{_id:'$children._id', dateofbirth:'$children.dateofbirth', givenname:'$children.givenname', isalive:'$children.isalive'}"); var aggregate = collection.aggregate().match(x => x.id == f.id) // .project(x => new { kids = x.children }) .unwind("children").sort(sort).limit(1).project<child>(project); console.writeline(aggregate.tostring()); var result = aggregate.firstordefault(); var pojectionisalive = bsondocument.parse( "{_id:1, name:1, children:{$filter:{ input:'$children', as:'kids', cond:{$eq:['$$kids.isalive', true]}}}}"); var kids = collection.aggregate().match(x => x.id == f.id).project<family>(pojectionisalive).tolist();
Comments
Post a Comment