将 object 插入嵌入文档

Inserting object into embedded document

我正在尝试学习 C# 的 mongoDB driver。第一次在 NoSQL 数据库上使用 driver。我试图在另一个 object 内的 collection 内插入一个 object,但无法让它工作。我一直在寻找没有运气的例子。

当前代码:

    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; }
    }

Driver代码 下面不会编译,但这是我想要做的。

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;
    }
}

试试这个:

var query = Query<PlayList>.EQ(e => e.Id, playListId);
var update = Update<PlayList>.Push(e => e.UrlList, url);

collection.Update(query, update);