Thursday 7 May 2015

MongoDB M101N Final Exam Question 8

Question 8:

Supposed we executed the following C# code. How many animals will be inserted into the "animals" collection?

using MongoDB.Bson;
using MongoDB.Driver;
using System.Threading.Tasks;

namespace M101DotNet
{
    class InsertTest
    {
        static void Main(string[] args)
        {
            MainAsync(args).GetAwaiter().GetResult();
        }

        static async Task MainAsync(string[] args)
        {
            var client = new MongoClient();
            var db = client.GetDatabase("test");

            var animals = db.GetCollection<BsonDocument>("animals");

            var animal = new BsonDocument
                            {
                            {"animal", "monkey"}
                            };

            await animals.InsertOneAsync(animal);
            animal.Remove("animal");
            animal.Add("animal", "cat");
            animal["_id"] = ObjectId.GenerateNewId();
            await animals.InsertOneAsync(animal);
            animal.Remove("animal");
            animal.Add("animal", "lion");
            animal["_id"] = ObjectId.GenerateNewId();
            await animals.InsertOneAsync(animal);
        }
    }
}


Options:

  • 0
  • 1
  • 2
  • 3
Solution: 

 Answer is 3

Note: I recommend to test your code once by creating a simple console application, because your code might be different from above example.

Explanation: Once the document is inserted in collection, we remove that document from animal object and add a new one, after that to make sure that the _id does not violate the unique constraint, there is a provision to generate new _id everytime the document is inserted, so all three documents will be inserted with new _id successfully


3 comments:

  1. Note the question this year (2016) does not include

    animal["_id"] = ObjectId.GenerateNewId();

    so if you run it as is it inserts the first record and then throws a duplicate key error.

    ReplyDelete
  2. Now the answer here was 1
    Cheers

    ReplyDelete
  3. it causes a duplicate key error... hence only one entry is inserted

    ReplyDelete