如果嵌入文档的插入中存在元素,则抛出错误

时间:2015-03-02 13:51:32

标签: c# mongodb mongodb-.net-driver

我想更新嵌入式文档,如果具有相同参数的元素已经存在且查询尽可能少,则抛出错误。

我尝试了以下内容。 :

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或者这个元素不存在的东西并且提出某种错误/警告 。不确定如何在没有首先尝试查找此元素并抛出错误(如果存在)的情况下完成此操作。 Mabey是唯一的出路吗?

Anny建议是受欢迎的,我是Mongo和MongoC#驱动程序的新手。

2 个答案:

答案 0 :(得分:2)

我不太了解C#,但对我而言,您的代码和说明并不匹配。如果&#34;具有相同参数名称的元素&#34;您说要抛出错误(作为什么?)已经存在,但在代码中你的检查是否有一些结果集有&gt; 0结果,而不是检查具有相同参数名称&#34;的某个&#34;元素的任何结果文档。我认为您只想更新文档,如果它没有您要在文档上设置的字段?以下是mongo shell代码中的一个示例,因为我不太了解C#:

> db.test.drop()
> db.test.insert({ "_id" : 0, "flavor" : "vanilla" })
> db.test.insert({ "_id" : 1 }) // no flavor
> db.test.update({ "_id" : 0, "flavor" : { "$exists" : false } }, 
                 { "$set" : { "flavor" : "chocolate" } })
// no documents update - flavor field existed in doc w/ _id 0
> db.test.update({ "_id" : 1, "flavor" : { "$exists" : false } }, 
                 { "$set" : { "flavor" : "chocolate" } })
// doc w/ _id 1 updated
> db.test.find().pretty()
{ "_id" : 0, "flavor" : "vanilla" }
{ "_id" : 0, "flavor" : "chocolate" }

答案 1 :(得分:1)

Whynot使用Ensure Index?我正在使用mongoC,但也许在c#中是这样的:

import java.io.*;
import java.util.Scanner;


public class dataReader {

    public static void main(String args[]) throws Exception {
        File fileName;
        fileName = new File("data.txt");
        PrintWriter outputFile;
        outputFile = new PrintWriter(fileName);

        File errorFile;
        errorFile = new File("errors.txt");
        PrintWriter outputErrorFile;
        outputErrorFile = new PrintWriter(errorFile);

        Scanner inputFile;



        int recordNumber = 0;


        String inputData;



        outputFile.println(77);
        outputFile.println("Fred");
        outputFile.println(92);
        outputFile.println("Wilma");
        outputFile.println(89.9);
        outputFile.println("Barney");
        outputFile.println(42);
        outputFile.println("BettyS");

        inputFile = new Scanner(fileName);

        while (inputFile.hasNext()) {

            recordNumber++;

            try {
                inputData = inputFile.nextLine();
                if (Integer.parseInt(inputData) < 50) {

                    outputErrorFile.println(recordNumber + ", " + inputData + ", is less than 50.");
                } else if (Integer.parseInt(inputData) > 90) {
                    outputErrorFile.println(recordNumber + ", " + inputData + ", is less than 50.");
                }
            } catch (Exception e) {
                outputErrorFile.println(recordNumber + ",  That's not an integer.");
            }

        }



        outputFile.close();
        outputErrorFile.close();


        System.out.println("Program terminated.");

    }
}