using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver.Builders; // needed for the method Query
namespace ConsoleMongo1
{
class Program
{
static void Main(string[] args)
{
MongoServer server = MongoServer.Create();
server.Connect();
var db = server.GetDatabase("console1");
var collect = db.GetCollection<Name>("names");
Console.Write("First name: ");
string first = Console.ReadLine();
Console.Write("Last name: ");
string last = Console.ReadLine();
Name input = new Name() { FirstName = first, LastName = last };
var query = Query.And(Query<Name>.EQ(n => n.FirstName, first), Query<Name>.EQ(n => n.LastName, last));
long dupCount = collect.FindAs<Name>(query).Count();
if (dupCount != 0)
{
Console.WriteLine("{0} {1} is already on file", first, last);
Console.WriteLine("dupCount = {0}", dupCount);
}
else
{
Console.WriteLine("Proceeding...");
collect.Save<Name>(input);
Console.WriteLine("{0} {1} has been added", first, last);
}
Console.WriteLine("Names include: ");
foreach (Name name in collect.FindAllAs<Name>())
{
Console.WriteLine("{0} {1} {2}", name.Id, name.FirstName, name.LastName);
}
}
}
class Name
{
[BsonId]
public ObjectId Id { get; set; }
[BsonElement("FirstName")]
public string FirstName { get; set; }
[BsonElement("LastName")]
public string LastName { get; set; }
}
}
For this program, I used the NuGet package "mongocsharpdriver", which involves a number of DLLs. Instead of JSON, MongoDB stores data as memory-mapped Bson. Note that I used an ObjectId document key instead of string. Also, I had to tag that field as BsonId.
MongoDB uses 3 layers: Server, Database and Collection. Collections are analogous to relational database tables. Unlike CouchDB, anything that needs to be created automatically is.
The query object I used was contained in the MongoDB.Driver.Builders namespace. I used the object-oriented domain object approach, using lambda functions to specify the search parameters. Feeding the query into the FindAs function located all the matches, which I then had Mongo count. FindAllAs located every Name object in the Collection.
Unlike LoveSeat, this API allowed me to specify a type when I stored the user data. On the other hand, this driver needed more DLLs. As in CouchDB, the document key was automically generated. However, in other architectures, you might need to recast the Mongo document IDs as Strings to keep the environment happy... like ASP.NET MVC, for example.
No comments:
Post a Comment