我正在尝试学习C#的mongoDB驱动程序。第一次在NoSQL数据库上使用驱动程序。我试图在一个集合中插入另一个对象内的对象,但是无法让它工作。我一直在寻找没有运气的例子。
当前代码:
public class PlayList
{
[BsonId(IdGenerator = typeof(CombGuidGenerator))]
public Guid Id { get; set; }
[BsonElement("Name")]
public string Name { get; set; }
[BsonElement("Owner")]
public Guid Owner { get; set; }
[BsonElement("UrlList")]
public List<Url> UrlList { get; set; }
//Curret URL info.
[BsonElement("CurrentUrl")]
public string CurrentUrl { get; set; }
[BsonElement("version")]
public Guid version { get; set; }
[BsonElement("time")]
public string time { get; set; }
[BsonElement("isRepeat")]
public bool isRepeat { get; set; }
}
}
public class Url
{
[BsonId(IdGenerator = typeof(CombGuidGenerator))]
public Guid Id { get; set; }
[BsonElement("Url")]
public string UrlPart { get; set; }
[BsonElement("Title")]
public string Title { get; set; }
}
驱动程序代码 下面不会编译,但它是我想要做的。
public void AddUrlToList(Url url, Guid playListId)
{
MongoCollection<PlayList> collection = GetPlayListForEdit();
try
{
//No idea how to insert the url object into the playlist collection of urls.
var q1 = Query<PlayList>.EQ(e => e.Id, playListId);
var editList = collection.Find(query);
var q2 = Query<PlayList>.EQ(e => e.UrlList); // not sure how to query inner collection
editList. /// select inner collection
/// Insert the Url Object into it .. . //collection.Insert(url);
/// Done .
}
catch (MongoCommandException ex)
{
string msg = ex.Message;
}
}
答案 0 :(得分:3)
试试这个:
var query = Query<PlayList>.EQ(e => e.Id, playListId);
var update = Update<PlayList>.Push(e => e.UrlList, url);
collection.Update(query, update);