项目update到了mongodb c# driver 2.2 , 发现从1.9到2.0的变化还是很大的,整合了一些常用的操作附加demo代码:
class program
{
const string collectionname = "video";
static void main(string[] args)
{
// remove the demo collection then recreate later
db.getcollection<video>(collectionname).database.dropcollection(collectionname);
var videos = new list<video>
{
new video { title="the perfect developer",
category="scifi", minutes=118 },
new video { title="lost in frankfurt am main",
category="horror", minutes=122 },
new video { title="the infinite standup",
category="horror", minutes=341 }
};
console.writeline("insert videos ...");
db.getcollection<video>(collectionname).insertmany(videos);
console.writeline("[after insert] all videos : ");
var all = db.getcollection<video>(collectionname).find(x=>x.title != string.empty).tolist();
foreach (var v in all)
{
console.writeline(v);
}
console.writeline("group by...");
var groupby = db.getcollection<video>(collectionname).aggregate()
.group(x => x.category, g => new {name = g.key, count = g.count(), totalminutes = g.sum(x => x.minutes)})
.tolist();
foreach (var v in groupby)
{
console.writeline(v.name + "," + v.count + "," + v.totalminutes);
}
console.writeline("updating one [title = the perfect developer]...");
// updating title with "the perfect developer" video's 'title' and 'minute'
db.getcollection<video>(collectionname).findoneandupdate(x=>x.title == "the perfect developer",
builders<video>.update.set(x=> x.title , "a perfect developer [updated]")
.addtoset(x => x.comments, "good video!")
.addtoset(x => x.comments, "not bad"));
console.writeline("[after updating one] all videos : ");
all = db.getcollection<video>(collectionname).find(x => x.title != string.empty).tolist();
foreach (var v in all)
{
console.writeline(v);
}
console.writeline("deleting one... [minutes = 122]");
db.getcollection<video>(collectionname).deleteone(x => x.minutes == 122);
console.writeline("[after deleting one] all videos : ");
all = db.getcollection<video>(collectionname).find(x => x.title != string.empty).tolist();
foreach (var v in all)
{
console.writeline(v);
}
console.read();
}
private static imongodatabase db
{
get
{
var url = new mongourl(configurationsettings.appsettings["mongourl"]);
var client = new mongoclient(url);
return client.getdatabase(url.databasename);
}
}
}
[bsonignoreextraelements]
public class video
{
public video()
{
comments = new list<string>();
}
[bsonid]
[bsonrepresentation(bsontype.objectid)]
public string id { get; set; }
public string title { get; set; }
public string category { get; set; }
public int minutes { get; set; }
public ilist<string> comments { get; set; }
public override string tostring()
{
return string.format("{0} - {1} - {2}", title, category, minutes);
}
}
对于mongodb c# driver从1.9到2.0的更新,简化了数据库的连接方式,简化了find,update,delete的接口,group by和projection操作也更流畅了。
在builders8742468051c85b06f0a0af9e3e506b5c中整合了 update, filter, projection, 和sort,功能的内聚性更强了,找function很方便。
以上就是mongodb c# driver 使用示例 (2.2)的内容。