是否有一种直接的方法来更新MongoDB中嵌套的实体array.我使用MongoDB C# Driver从应用程序调用DB.下面是一个exmaple:假设我有一个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"
    }}

Right now, am reading the entire nested array of courses -> doing the modification at application end -> then passing the entire array for update with the filedname "Courses" which is going to replace the existing array with the one passed.

但我在想,有没有一种方法可以用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; }
}

查找Mongo文档中的positional operator个.

  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);

Mongodb相关问答推荐

MongoDB更新对象数组

在MongoDB中是否可以按递增顺序更新多个文档?

在单个mongo文档中组合数组与聚合

如何更新mongo中列表最后一个对象的属性

Golang:如何判断 collection.Find 是否没有找到任何文件?

如何使用 Golang 库获取 MongoDB 版本?

MongoDB 支持的最 Big Data 库数

MongoID find 或 find_by

如何将记录从一个 mongo 数据库插入另一个?

使用 homebrew 和 Xcode 8.1.1 安装 Mongodb 失败

在 Heroku 上使用 Node 读取、写入和存储 JSON

python mongodb正则表达式:忽略大小写

如何使用原子操作在一个文档中切换布尔字段?

MongoDB:多个 $elemMatch

使用 Mongoid 和 Ruby 查询最近 30 天的日期范围?

使用 MongoDB Java 驱动程序将 DBObject 转换为 POJO

MongoDB - 我如何找到另一个集合中的文档未引用的所有文档

如何从 Mongoose 模型对象中获取集合名称

MongoTemplate upsert - 从 pojo 进行更新的简单方法(哪个用户已编辑)?

将新值推送到 mongodb 内部数组 - mongodb/php