简体   繁体   English

C# 驱动程序 2.0 Mongodb UpdateOneAsync

[英]C# driver 2.0 Mongodb UpdateOneAsync

public class Student
{
    public long StudentId {get; set;}
    public string Fname {get; set;}
    public string Lname {get; set;}
    public List<ObjectId> CoursesList {get; set;}
    public int IQ {get;set;}
}

public class Courses
{
    [BsonId]
    public ObjectId Id { get; set; }
    public string CourseNumber{get; set;}
    public string CourseName{get; set;}
}

How do I add/append a courser Id to Course list(which may be null for the first time) of a Student object如何将课程 ID 添加/附加到学生对象的课程列表(第一次可能为空)

PS: I know how to set a field using the below command. PS:我知道如何使用以下命令设置字段。 I am hoping it is on similar lines for the above problem我希望它与上述问题类似

await StudentCollection.UpdateOneAsync(a => a.StudentId == studentId, Builders<Student>.Update.Set( a => a.IQ,90));

As you've already discovered, the C# code to use $addToSet is:正如您已经发现的,使用 $addToSet 的 C# 代码是:

var filter = Builders<Student>.Filter.Eq(s => s.StudentId, studentId);
var update = Builders<Student>.Update.AddToSet(s => s.CoursesList, courseId);
var result = await collection.UpdateOneAsync(filter, update);

However, $addToSet is not going to work if the CourseList member has been stored in the collection as a null.但是,如果 CourseList 成员已作为 null 存储在集合中,则 $addToSet 将不起作用。 The server requires that the existing value for $addToSet be an array (it can be an empty array).服务器要求 $addToSet 的现有值是一个数组(它可以是一个空数组)。

The easiest solution is to just store an empty list for CoursesList instead of a null when there are no courses.最简单的解决方案是只为 CoursesList 存储一个空列表,而不是在没有课程时为空。

This is working for me.这对我有用。 When you define "List" like this, it will be empty and works with AddToSet/Push methods.当您像这样定义“列表”时,它将为空并与 AddToSet/Push 方法一起使用。

public List<ObjectId> CoursesList = new List<ObjectId>();

The only case that you have to pay attention is when the array CourseList is null, in this case you have to use the code below (see also here) :您必须注意的唯一情况是数组 CourseList 为空时,在这种情况下,您必须使用以下代码(另请参见此处)

var newListOfObject = new List<ObjectId>(){...}
await StudentCollection.UpdateOneAsync(a => a.StudentId == studentId, Builders<Student>.Update.Set( a => a.CoursesList, newListOfObject));

Otherwise you can use AddToSet or Push like explain in the other answers.否则,您可以在其他答案中使用 AddToSet 或 Push 之类的解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM