1

考虑以下学生和教师的简单示例;

// person
public class Person
{
    public ObjectId Id { get; set; }
    public string Name { get; set; }
    public Person() {
        Id = ObjectId.GenerateNewId(DateTime.Now);
    }
}

// student has a Classroom
public class Student : Person
{
    public string Classroom { get; set; }
}

// teacher has a Dictionary<ObjectId, Student> Students
public class Teacher : Person
{
    [BsonDictionaryOptions(DictionaryRepresentation.ArrayOfDocuments)]
    public Dictionary<ObjectId, Student> Students { get; set; }
    public Teacher() {
        Students = new Dictionary<ObjectId, Student>();
    }
}

class Program
{
    static void Main(string[] args)
    {

        var server = MongoServer.Create("mongodb://localhost/database?safe=true");
        var database = server.GetDatabase("sandbox");
        var collection = database.GetCollection<Teacher>("teachers");
        collection.Drop();

        // create students
        var s1 = new Student() { Name = "s1", Classroom = "foo" };
        var s2 = new Student() { Name = "s2", Classroom = "foo" };
        var s3 = new Student() { Name = "s3", Classroom = "baz" };
        var s4 = new Student() { Name = "s4", Classroom = "foo" };

        // teacher 1
        var t1 = new Teacher() { Name = "t1" };
        t1.Students.Add(s1.Id, s1);
        t1.Students.Add(s2.Id, s2);
        collection.Insert(t1);

        // teacher 2
        var t2 = new Teacher {Name = "t2"};
        t2.Students.Add(s3.Id, s3);
        collection.Insert(t2);

        // add teacher 3 
        var t3 = new Teacher() {Name = "t3"};
        t3.Students.Add(s4.Id, s4);
        collection.Insert(t3);

        // select via key
        var onlyt1 = collection.AsQueryable().Where(t => t.Students.ContainsKey(s1.Id)).ToList();

        Console.WriteLine("onlyt1 : {0}", onlyt1.ToJson());
        Console.ReadLine();
    }
}

我可以通过键(如上所示)进行选择,但是我如何找到所有有“foo”教室的学生的老师?我想写一些类似的东西;

// select via value
var shouldBeJustT1andT3 = collection.AsQueryable().Where(t => t.Students.Values.Where(s => s.Classroom == "foo")).ToList(); 
4

2 回答 2

2

您可以使用Any来获取在给定教室“foo”中有学生的任何老师:

List<Teacher> shouldBeJustT1andT3 = collection.Where(
    teacher => teacher.Students.Any(student => student.Classroom == "foo")
).ToList(); 

编辑

由于 Mongo 的 IQueryable 默认不支持Any,也许你可以使用WhereandCount而不是Any

List<Teacher> shouldBeJustT1andT3 = collection.Where(
    teacher => teacher.Students.Where(student => student.Classroom == "foo").Count() > 0
).ToList(); 
于 2012-11-29T22:43:30.380 回答
0

你不能有Students类型ICollection<Person>吗?

那么你不需要查询字典的值,而是平面对象的列表,即where s.ID == x && s.Classroom == "blah".

字典仅通过键查找对象才有意义,即t.Students[studentId].


找老师:看dbaseman的回答,他是对的。

于 2012-11-29T22:44:08.973 回答