2

I'm trying to learn the mongoDB driver for C#. First time using the driver on a NoSQL database. I'm trying to insert an object inside a collection inside another object but cant get it to work. I have been searching for examples with no luck.

Current Code :

    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 code Below wont compile but it's what I want to do.

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

1 Answer 1

3

Try this:

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

collection.Update(query, update);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks alot. Do you mabey have some good resource where there are some examples of basic syntax using the mongo driver? :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.