我完全迷失了使用c#驱动程序在mongodb中对嵌入式数组中的数组元素进行CRUD和其他操作。
鉴于我有以下类(简单示例):
public class Child
{
public ObjectId Id;
public DateTime dateOfBirth;
public string givenName;
}
class Family
{
public ObjectId Id;
public string name;
public List<Child> children;
}
我的收藏品应存储家庭文件。
我如何:
不加载整个Family对象
虽然我正在参加mongo大学课程mongo.net但我完全迷失了,并且几乎没有关于使用数组的文档。
我知道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();
答案 0 :(得分:2)
1-4由你确定 - 恭喜! 请查看聊天中讨论的5和6。
中的完整代码 var f = GenerateFaimly();
collection.InsertOne(f);
var sort = BsonDocument.Parse("{\"kids.dateOfBirth\": -1}"); // get the 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();