Example #1
0
        /// <summary>
        /// [MONGODB-DEMO] Strongly typed collection and LINQ.
        /// </summary>
        private static async Task UsingOfLINQ(IMongoDatabase db)
        {
            Console.WriteLine("\nStrongly typed collection and LINQ:");
            var person = new PersonPlain
            {
                Age = 11,
                Name = "Anrew"
            };

            var collection = db.GetCollection<PersonPlain>(TYPED_COLLECTION_NAME); // 2) Strongly TYPED collection !!
            await collection.InsertOneAsync(person);
            long count = await collection.CountAsync(new BsonDocument());
            Console.WriteLine("\n[DB]{0}.[Collection]{1} : collection.Count = {2}", collection.Database.DatabaseNamespace.DatabaseName, collection.CollectionNamespace.CollectionName, count);

            var list = await collection.Find(p => p.Age < 30 && p.Name != "Sergii").ToListAsync();

            // interface IMongoQueryable<T> : IQueryable<T>, IEnumerable<T>
            var linq = await collection.AsQueryable().Where(p => p.Age < 30 && p.Name != "Sergii").ToListAsync();
        }
Example #2
0
        /// <summary>
        /// [MONGODB-DEMO] The mapping from POCOs to Bson in run-time (!! this might help to break off relationship between a particular DB and Model classes).
        /// </summary>
        private static void PocoPlainSerialization()
        {
            // A convention that sets the element name the same as the class-member name with the first character lower cased.
            var conventionPack = new ConventionPack();
            conventionPack.Add(new CamelCaseElementNameConvention());
            ConventionRegistry.Register("camelCase", conventionPack, type => type.IsPublic);

            // Register BsonClassMap for the concrete class.
            // The same you can achieve with using of attributes. See class Person.
            BsonClassMap.RegisterClassMap<PersonPlain>(cm =>
            {
                cm.AutoMap();
                cm.MapMember(c => c.Name).SetElementName("new_name");
                cm.MapMember(c => c.Age).SetIgnoreIfDefault(true);
            });

            var person = new PersonPlain
            {
                Id = ObjectId.GenerateNewId(),
                Name = "Benny",
                Age = 0, // 33,
                Colors = new List<string> { "red", "blue" },
                Pets = new List<PetPlain>
                    {
                        new PetPlain { Name = "Fluffy",    Type = "dog" },
                        new PetPlain { Name = "Garfield",  Type = "cat" }
                    },
                ExtraElements = new BsonDocument("additionalName", "Name2")
            };

            using (var writer = new JsonWriter(Console.Out))
            {
                BsonSerializer.Serialize(writer, person);
            }

            Console.WriteLine();
        }