예제 #1
0
        public async Task InsertWithDuplicateKey()
        {
            /* In a concurrent system, your app might try to save a document that
             * has a duplicate value on a field that is marked unique. When this
             * happens, MongoDB returns a Duplicate Key error.
             *
             * To show this, let's add a Theater document to a collection, and
             * then add a new document with the same Id value as the first
             * Theater. We're using the Id field because it maps to the _id field
             * in Mongo, and _id is a field that is always marked as unique.
             */

            var testTheater = new Theater(10101010, "234 Bar Ave.", "Wishywashy", "WY", "87654");
            await _theatersCollection.InsertOneAsync(testTheater);

            /* You may recall from a previous lesson that in our Theater class,
             * we don't assign a value to the Id field; we let MongoDB do that
             * for us. When the call to InsertOne or InsertOneAsync returns,
             * our new Theater object has that field populated for us!
             *
             * So let's now use that existing Id value to create and insert a
             * new Theater object:
             */

            var myNewTheater = new Theater()
            {
                Id = testTheater.Id
            };

            /* This call should fail with an exception:
             */

            Assert.Throws <MongoWriteException>(() =>
                                                _theatersCollection.InsertOne(myNewTheater));

            /* Now that we've confirmed this, we can wrap our writes in
             * try-catch blocks to handle exceptions accordingly. While a Duplicate
             * Key error is unlikely to happen, especially if you let MongoDB
             * handle assigning a value to the _id field for you, it's always a
             * best practice to use try-catch blocks. And if you are managing
             * a field of unique values in your code, you'll definitely want
             * to be handling this exception!
             */

            try
            {
                await _theatersCollection.InsertOneAsync(myNewTheater);
            }
            catch (MongoWriteException ex)
            {
                /* There are, of course, other potential write errors, so
                 * let's make sure we really caught a dupliate key error:
                 */
                Assert.IsTrue(ex.Message.Contains("E11000 duplicate key error"));

                /* If you have a custom process for generating unique key values,
                 * this would be a good place to change the Id value and re-try
                 * the Insert.
                 */
            }
        }
예제 #2
0
        public async Task CreateMovieAsync()
        {
            /* There are two methods for writing documents with the MongoDB
             * driver: InsertOne and InsertMany, as well as the Async versions
             * of those two methods. In this lesson, I'll show you how to use
             * the Async methods in a couple of different ways.
             *
             * Let's start with a simple example. We want to add a new movie
             * theater to the "theaters" collection. Let's first take a look at
             * the Theater mapping class. It has Id, TheaterId, and Location
             * properties. The Location property is an object that contains an
             * Address object and Geo information, which we won't worry about
             * in this lesson.
             *
             * With that bit of information, let's create a new instance of the
             * Theater class, using the constructor that takes in a TheaterId and
             * various Address components:
             *
             */

            var newTheater = new Theater(27777,
                                         "4 Privet Drive",
                                         "Little Whinging",
                                         "LA",
                                         "343434");

            // And now we call InsertOneAsync() to add it to the collection:
            await _theatersCollection.InsertOneAsync(newTheater);

            /* Here's something you should be aware of. In the constructor for
             * the Theater object, we don't set the Id property. Instead,
             * we let MongoDB create one and assign it for us as part of the
             * Insert call. We can check that property as soon as the InsertOne
             * returns:
             */

            Assert.IsNotEmpty(newTheater.Id.ToString());


            /* Adding multiple theaters to the collection is just as easy.
             * Let's add a group of 3 new theaters that have just been built.
             * First, we create the Theater objects:
             */

            var theater1 = new Theater(27017, "1 Foo Street", "Dingledongle", "DE", "45678");
            var theater2 = new Theater(27018, "234 Bar Ave.", "Wishywashy", "WY", "87654");
            var theater3 = new Theater(27019, "75 Birthday Road", "Viejo Amigo", "CA", "99887");

            /* And then we call InsertManyAsync, passing in a new List of
             * those Theater objects:
             */

            await _theatersCollection.InsertManyAsync(
                new List <Theater>()
            {
                theater1, theater2, theater3
            }
                );

            /* Let's make sure everything worked. */

            var newTheaters = await _theatersCollection.Find <Theater>(
                Builders <Theater> .Filter.Gte(t => t.TheaterId, 27017)
                & Builders <Theater> .Filter.Lte(t => t.TheaterId, 27019))
                              .ToListAsync();

            Assert.AreEqual(3, newTheaters.Count);
            Assert.AreEqual("1 Foo Street",
                            newTheaters.First().Location.Address.Street1);
            Assert.AreEqual("Viejo Amigo",
                            newTheaters.Last().Location.Address.City);


            /* So that's all there is to writing new documents to a MongoDB
             * collection. In the next lesson, we'll look at updating
             * existing documents.
             */
        }