is there straight forward way update nested array of entities in mongodb. using mongodb c# driver
making db call application. below exmaple : have student
collection each document has nested array of course
necessary fields populated , course
separate collection like:
{ "_id": "234dssfcv456", "name": "jean douglas", "age": 32, "courses": [ { "_id": "1234", "name": "computer science", "level": "basic" }, { "_id": "3456", "name": "bio science", "level": "intermediate" } ] }
i know can update nested entity index below don't know index , rather know nested course
object id
only.
db.college.student.update( {"student._id": "234dssfcv456"}, {$set: { "student.$.courses.1.level": "basic" }}
right now, reading entire nested array of courses -> doing modification @ application end -> passing entire array update filedname "courses"
going replace existing array 1 passed.
but thinking, there way can update 1 entity in array id
available. please suggest.
*** on right side in related question section shows updating nested array of objects using index of object item not possibility me.
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 schema:
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; } }
lookup mongo docs positional operator. driver higher version 2.2.3.3 using:
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 id , course id var student = _students.find(studentidandcourseidfilter).singleordefault(); // update positional operator var update = builders<student>.update; var courselevelsetter = update.set("courses.$.level", "updated level"); _students.updateone(studentidandcourseidfilter, courselevelsetter);
Comments
Post a Comment