Skip to content

Instantly share code, notes, and snippets.

@baluubas
Last active September 19, 2016 17:09
Show Gist options
  • Save baluubas/155b443f275e4fd0502b8094ce6a8a47 to your computer and use it in GitHub Desktop.
Save baluubas/155b443f275e4fd0502b8094ce6a8a47 to your computer and use it in GitHub Desktop.
MongoDB driver with DocumentDB
using System;
using MongoDB.Bson;
using MongoDB.Driver;
namespace ConsoleApp1
{
public class Program
{
public static void Main(string[] args)
{
MongoClient client = new MongoClient("<CONNETION STRING>");
var database = client.GetDatabase("test-db");
var userId = Guid.NewGuid();
var documentId = Guid.NewGuid();
var collection = database.GetCollection<BsonDocument>("test-collection");
var doc = new BsonDocument
{
{"_id", documentId },
{ "members",
new BsonArray {
new BsonDocument() {
{ "userId", userId }
}
}
}
};
collection.InsertOneAsync(doc).Wait();
Console.WriteLine("Inserted document, press any key to find document");
Console.ReadKey();
var filter = Builders<BsonDocument>.Filter.Eq("_id", documentId);
var result = collection.FindAsync(filter).Result.FirstOrDefault();
Console.WriteLine("Find by id:");
Console.WriteLine(result);
var filter2 = Builders<BsonDocument>.Filter.Eq("members.userId", userId);
var result2 = collection.FindAsync(filter2).Result
.FirstOrDefault();
Console.WriteLine("Find by userId:");
// Expecting to find the document again.
Console.WriteLine(result2 == null ? "No results" : result2.ToString());
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment