MongoDB

MongoDB C# Driver Cheat Sheet by Derek Hunziker

The following is a comparison between the MongoDB shell and C# Driver. I tried to focus on syntax that you might encounter while building out a data access object (such as CRUD), as opposed to a comprehensive list of every shell command. The C# driver also includes LINQ support, however, I choose not to include it since it is pretty well known.

The C# examples assume the use of strictly-typed classes and Query<> builders wherever possible, instead of BsonDocuments and "magic strings", which don't provide much in terms of compile-time safety. Check out the C# Driver Documentation for more info on how to map classes to BsonDocuments using property Attributes or Class Maps.

Please note that most of the C# examples are condensed down as much as possible for the sake of brevity. 

FeatureMongoDB Shell v.2.6.5C# Driver v1.9.2
INSERT
Basic Insert
db.users.insert(
  {
    name: "Derek", 
    email: "derek@example.com"
  }
)
var user = new User
{ 
    Name = "Derek",
    Email = "derek@example.com"
};
db.GetCollection<User>("users").Insert(user);
Insert w/ ID
db.users.insert(
  {
    _id: 10,
    name: "Derek",
    email: "derek@example.com"
  }
)
var user = new User
{
    Id = 10, // [BsonId] attribute applied
    Name = "Derek",
    Email = "derek@example.com"
};
db.GetCollection<User>("users").Insert(user);
Insert Nested
db.users.insert(
  {
    _id: 100,
    name: "Derek",
    email: "derek@example.com",
    address: {
      city: "Portland",
      state: "OR",
      zip: "97232"
    }
  }
)
var user = new User
{
    Id = 100, // [BsonId] attribute applied
    Name = "Derek",
    Email = "derek@example.com",
    Address = new Address
    {
        City = "Portland",
        State = "OR",
        Zip = "97232"
    }
};
db.GetCollection<User>("users").Insert(user);

Bulk Insert
db.products.insert(
  [
    { item: "pencil", qty: 5 },
    { item: "pen", qty: 20 },
    { item: "eraser", qty: 25 }
  ]
)
db.GetCollection<Product>("products").InsertBatch(
        new []
        {
            new Product { Item = "pencil", Qty = 5 },
            new Product { Item = "pen", Qty = 20 },
            new Product { Item = "eraser", Qty = 25 }
        }
    );
Write Concern
db.users.insert(
  { 
    name: "Derek",
    email: "derek@example.com" 
  },
  { 
    writeConcern: { 
      w: "majority", 
      wtimeout: 5000 
    } 
  }
)
var user = new User
{
    Name = "Derek", 
    Email = "derek@example.com"
};
var collection = db.GetCollection<User>("users");
var result = collection.Insert(
    user, 
    new WriteConcern
    {
        W = WriteConcern.WMajority.W, 
        WTimeout = TimeSpan.FromSeconds(5)
    }
);
FIND & QUERY OPERATORS
Find One
db.users.findOne(
  {
    _id: 10
  }
)
var collection = db.GetCollection<User>("users");
var query = Query<User>.EQ(u => u.Id, 10);
User user = collection.FindOne(query);
Find Nested
db.users.find(
  {
    "address.state": "OR"
  }
)
var collection = db.GetCollection<User>("users");
var query = Query<User>.EQ(u => u.Address.State, "OR");
MongoCursor<User> cursor = collection.Find(query);
Find All
db.users.find()
var collection = db.GetCollection<User>("users");
MongoCursor<User> cursor = collection.FindAll();
Find Array
db.products.find(
  {
    colors: "blue"
  }
)
var collection = db.GetCollection<Product>("products");
// NOTE: p.Colors is of type string[]
var query = Query<Product>.EQ(p => p.Colors, "blue");
MongoCursor<Product> cursor = collection.Find(query);
$all
db.products.find(
  {
    colors: {
      $all: ["blue", "orange"]
    }
  }
)
var collection = db.GetCollection<Product>("products");
var targetColors = new[] { "blue", "orange" };
var query = Query<Product>.All(p => p.Colors, targetColors);
MongoCursor<Product> cursor = collection.Find(query);
$and
db.users.find(
  {
    "name": "Derek",
    "address.state": "OR"
  }
)
var collection = db.GetCollection<User>("users");
var query = Query.And(
        Query<User>.EQ(u => u.Name, "Derek"),
        Query<User>.EQ(u => u.Address.State, "OR")
    );
MongoCursor<User> cursor = collection.Find(query);
$or
db.users.find(
  {
    $or: [
      { name: "Derek" },
      { name: "John" }
    ]
  }
)
var collection = db.GetCollection<User>("users");
var query = Query.Or(
        Query<User>.EQ(u => u.Name, "Derek"),
        Query<User>.EQ(u => u.Name, "John")
    );
MongoCursor<User> cursor = collection.Find(query);
$and / $or
db.products.find(
  {
    type: "office",
    $or: [
      { item: "pen" },
      { qty: 25 }
    ]
  }
)
var collection = db.GetCollection<Product>("products");
var query = Query.And(
        Query<Product>.EQ(p => p.Type, "office"),
        Query.Or(
            Query<Product>.EQ(p => p.Item, "pen"),
            Query<Product>.EQ(p => p.Qty, 25)
        )
    );
MongoCursor<Product> cursor = collection.Find(query);
$gt
db.products.find(
  {
    qty: { $gt: 5 }
  }
)
var collection = db.GetCollection<Product>("products");
var query = Query<Product>.GT(p => p.Qty, 5);
MongoCursor<Product> cursor = collection.Find(query);
$exists
db.users.find(
  {
    name: { $exists: true }
  }
)
var collection = db.GetCollection<User>("users");
var query = Query<User>.Exists(u => u.Name);
MongoCursor<User> cursor = collection.Find(query);
$type
db.products.find(
  {
    item: { $type: 2 }
  }
)
var collection = db.GetCollection<Product>("products");
var query = Query<Product>.Type(p => p.Item, BsonType.String);
MongoCursor<Product> cursor = collection.Find(query);
$regex
db.products.find(
  {
    item: { $regex: "er$" }
  }
)
var collection = db.GetCollection<Product>("products");
var regex = new BsonRegularExpression("er$");
var query = Query<Product>.Matches(p => p.Item, regex);
MongoCursor<Product> cursor = collection.Find(query);
sort()
skip()
limit()
db.products.find().sort(
 {
   qty: 1,
   price: -1
 }  
).skip(2).limit(10)
var collection = db.GetCollection<Product>("products");
var sort = SortBy<Product>
                .Ascending(p => p.Qty)
                .Descending(p => p.Price);
MongoCursor<Product> cursor = collection
    .FindAll()
    .SetSortOrder(sort)
    .SetSkip(2)
    .SetLimit(10);
Field Projection
db.products.find(
  { },
  {
    _id: 0,
    item: 1
  }
)
var collection = db.GetCollection<Product>("products");
var fields = new FieldsBuilder<Product>()
    .Exclude(p => p.Id)
    .Include(p => p.Item);
MongoCursor<Product> cursor = collection
    .FindAll()
    .SetFields(fields);
UPDATE
Wholesale Update
db.products.update(
  {
    _id: 10
  },
  {
    type: "office",
    item: "pen"
    qty: 5,
    price: 2.99,
    colors: ["red", "green", "blue"]
  }
)
var collection = db.GetCollection<Product>("products");
var query = Query<Product>.EQ(p => p.Id, 10);
var product = new Product
{
    Id = 10, // Same ID required in C# driver
    Type = "office",
    Item = "pen",
    Qty = 5,
    Price = 2.99,
    Colors = new[] {"red", "green", "blue"}
};
var replacement = Update<Product>.Replace(product);
collection.Update(query, replacement);
$set
db.products.update(
  {
    _id: 10
  },
  {
    $set: { price: 0.75 }
  }
)
var collection = db.GetCollection<Product>("products");
var query = Query<Product>.EQ(p => p.Id, 10);
var set = Update<Product>.Set(p => p.Price, 0.50);
collection.Update(query, set);
Multi Update
db.products.update(
  {
    item: "pen"
  },
  {
    $set: {
      colors: ["black", "blue"]
    }
  },
  {
    multi: true
  }
)
var collection = db.GetCollection<Product>("products");
var query = Query<Product>.EQ(p => p.Item, "pen");
var myColors = new[] { "black", "blue" }
var set = Update<Product>.Set(p => p.Colors, myColors);
collection.Update(query, set, UpdateFlags.Multi);
$inc
db.product.update(
  {
    item: "pen"
  },
  {
    $inc: { price: 1 }
  },
  {
    multi: true
  }
)
var collection = db.GetCollection<Product>("products");
var query = Query<Product>.EQ(p => p.Item, "pen");
var inc = Update<Product>.Inc(p => p.Price, 1.0);
collection.Update(query, inc, UpdateFlags.Multi);
$push
db.products.update(
  {
    item: "pen"
  },
  {
    $push: { colors: "red" }
  },
  {
    multi: true
  }
)
var collection = db.GetCollection<Product>("products");
var query = Query<Product>.EQ(p => p.Item, "pen");
var push = Update<Product>.Push(p => p.Colors, "red");
collection.Update(query, push, UpdateFlags.Multi);
REMOVE
Basic Remove
db.products.remove(
  {
    _id: 10
  }
)
var collection = db.GetCollection<Product>("products");
var query = Query<Product>.EQ(p => p.Id, 10);
collection.Remove(query);
Just One
db.products.remove(
  {
    _id: 10
  },
  {
    justOne: true,
    writeConcern: {
      w: 0
    }
  }
)
var collection = db.GetCollection<Product>("products");
var query = Query<Product>.EQ(p => p.Id, 10);
collection.Remove(query, RemoveFlags.Single, WriteConcern.Unacknowledged);