如果具有相同參數的元素已儘可能少地存在查詢,我想更新嵌入式文檔並引發錯誤。如果嵌入式文檔插入時存在元素,則拋出錯誤
我試了下面。 :
public void AddUrlToList(Url url, Guid playListId)
{
MongoCollection<PlayList> collection = GetPlayListForEdit();
try
{
//DO better solution here...
var query = Query.EQ("UrlList.Url", url.UrlPart);
var items = collection.Find(query).ToList();
if (items.Count > 0)
throw new Exception();
//collection.Update(Query.And(Query<PlayList>.EQ(e => e.Id, playListId), Query.NE("UrlList", url.UrlPart)), Update.AddToSetWrapped("UrlList", url), WriteConcern.Acknowledged);
collection.Update(Query<PlayList>.EQ(e => e.Id, playListId), Update.AddToSetWrapped("UrlList", url));
}
catch (MongoCommandException ex)
{
string msg = ex.Message;
}
}
文件:
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
{
[BsonElement("Url")]
public string UrlPart { get; set; }
[BsonElement("Title")]
public string Title { get; set; }
}
但是我寧願想要做的outcommented排在那裏我有.NE什麼斷言風格的東西,這個元素不存在和thow某種錯誤/警告。不確定如何在沒有首先嚐試查找此元素並拋出錯誤(如果存在)的情況下執行此操作。 Mabey是唯一的出路嗎?
安妮的建議,歡迎來到Mongo和MongoC#驅動程序。