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 to add / add the cursor identifier to the list of courses (which may be empty for the first time) of the Student object

PS: I know how to set the field using the command below. I hope this will be the same for the above problem.

await StudentCollection.UpdateOneAsync(a => a.StudentId == studentId, Builders<Student>.Update.Set( a => a.IQ,90));
+4
source share
2 answers

As you already discovered, C # code to use $ addToSet:

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 will not work if the CourseList member was saved in the collection as null. The server requires that the existing value for $ addToSet be an array (this may be an empty array).

The easiest solution is to just keep an empty list for CoursesList instead of null when there are no courses.

+9

. "", , AddToSet/Push.

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

All Articles