在 MongoDB 的嵌套实体数组中更新 属性

Update property in nested array of entities in MongoDB

是否有直接的方法来更新 MongoDB 中的嵌套实体数组。我正在使用 MongoDB C# Driver 从应用程序进行数据库调用。下面是一个例子:假设我有一个 Student 集合,其中每个文档都有一个 Course 的嵌套数组,其中填充了一些必要的字段,并且 Course 本身是一个单独的集合,例如:

{
 "_id": "234dssfcv456",
 "Name": "Jean Douglas",
 "Age": 32,
 "Courses": 
  [
    {
       "_id": "1234",
       "Name": "Computer Science",
       "Level": "Basic" 
    },
    {
       "_id": "3456",
       "Name": "Bio Science",
       "Level": "Intermediate" 
    }
  ] 
}

我知道我可以通过索引更新嵌套实体,如下所示,但我不知道索引,而只知道嵌套 Course 对象 Id

db.College.Student.update(
    {"Student._id": "234dssfcv456"}, 
    {$set: {
        "Student.$.Courses.1.Level": "Basic"
    }}

现在,正在读取整个嵌套的课程数组 -> 在应用程序结束时进行修改 -> 然后将整个数组传递给 filedname "Courses" 以进行更新,这将替换现有数组一个通过了。

但我在想,有没有一种方法可以用 Id 可用更新数组中的一个实体。请提出建议。

*** 在 Related 问题部分的右侧,所有显示使用对象的 index 更新对象的嵌套数组这对我来说是不可能的。

Mongo shell:

> db.students.find( {_id:"234dssfcv456", "Courses._id":"1234"} ).pretty()
> db.students.update( {_id:"234dssfcv456", "Courses._id":"3456"}, { $set: { "Courses.$.Level" : "Updated" } } )

C# Mongo 架构:

public class Student {
  [BsonId]
  [BsonRepresentation(BsonType.String)]
  public string Id { get; set; }
  public string Name { get; set; }
  public int Age { get; set; }
  public Course[] Courses { get; set; }
}

public class Course {
  [BsonId]
  [BsonRepresentation(BsonType.String)]
  public string Id { get; set; }
  public string Name { get; set; }
  public string Level { get; set; }
}

positional operator 查找 Mongo 文档。 对于高于 2.2.3.3 版的驱动程序,我使用的是:

  var _client = new MongoClient(@"....");
  var _database = _client.GetDatabase("...");
  var _students =  _database.GetCollection<Student>("students");

  var filter = Builders<Student>.Filter;
  var studentIdAndCourseIdFilter = filter.And(
    filter.Eq(x => x.Id, "234dssfcv456"),
    filter.ElemMatch(x => x.Courses, c => c.Id == "1234") );
   // find student with id and course id
   var student = _students.Find(studentIdAndCourseIdFilter).SingleOrDefault();

  // update with positional operator
  var update = Builders<Student>.Update;      
  var courseLevelSetter = update.Set("Courses.$.Level", "Updated Level");
  _students.UpdateOne(studentIdAndCourseIdFilter, courseLevelSetter);

你也可以这样代替update.Set("Courses.$.Level", "Updated Level");

update.Set(x => x.Courses[-1].Level, "Updated Level");

来源:http://www.mattburkedev.com/updating-inside-a-nested-array-with-the-mongodb-positional-operator-in-c-number/