gpt4 book ai didi

c# - 将对象插入嵌入文档

转载 作者:可可西里 更新时间:2023-11-01 10:03:54 30 4
gpt4 key购买 nike

我正在尝试学习 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;
}
}

最佳答案

试试这个:

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

collection.Update(query, update);

关于c# - 将对象插入嵌入文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28765224/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com