Skip to content

Instantly share code, notes, and snippets.

@ryanbuening
Forked from ImsMoon/Example.cs
Created June 24, 2022 01:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanbuening/963b787affa7b40c30374282fb2c9d45 to your computer and use it in GitHub Desktop.
Save ryanbuening/963b787affa7b40c30374282fb2c9d45 to your computer and use it in GitHub Desktop.
Mongo C# Driver CRUD CheatSheet
//Read
//BsonDocument
var collection = db.GetCollection<BsonDocument>("people");
var builder = Builders<BsonDocument>.Filter;
//Note that the '&' '!' '|' operators are overloaded when used in the FilterBuilder
var filter = builder.Lt("Age", 33) & !builder.Eq("Name", "Ericsson");
var list = await collection.Find(filter).ToListAsync();
------------------------------------------------------------------------------------
//Strongly Typed
var collection = db.GetCollection<People>("people");
var list = await collection.Find(x => x.Age < 30 && x.Name != "Ericsson")
.ToListAsync();
------------------------------------------------------------------------------------
//Sorting
var collection = db.GetCollection<People>("people");
var list = await collection.Find(x => x.Age < 30 && x.Name != "Ericsson")
.SortBy(x => x.Age)
.ThenByDescending(x => x.Name)
.ToListAsync();
await collection.Find(builder.Eq("type", "homework"))
.Sort(Builders<BsonDocument>.Sort.Ascending("student_id").Ascending("score")); //do some async operation here
-------------------------------------------------------------------------------------
//Projections
var collection = db.GetCollection<People>("people");
var list = await collection.Find(new BsonDocument())
.Project(x => x.Name)
.ToListAsync();
//Everything except the calculation will be handeld server side. The calculation
list = await collection.Find(new BsonDocument())
.Project(x => new { x.Name, Calcage = x.Age + 20 })
.ToListAsync();
--------------------------------------------------------------------------------------
//Replace & Updates
var collection = db.GetCollection<Widget>("widgets");
var result = await collection.ReplaceOneAsync(
new BsonDocument("x", 10), //Where x is 10
new BsonDocument("x", 30), //x will be set to thirty
new UpdateOptions { IsUpsert = true}); //If with value 10 is non-existing x with value 30 will be inserted
//Alternative
var result = await collection.ReplaceOneAsync(
Builders<BsonDocument>.Filter.Eq("x", 10),
Builders<BsonDocument>.Filter.Eq("x", 30),
new UpdateOptions { IsUpsert = true});
//Update
//Increments the specified document where x is 5 to be 6
var result = await collection.UpdateOneAsync(
Builders<BsonDocument>.Filter.Eq("x", 5),
Builders<BsonDocument>.Update.Inc("x", 1));
//Increments the specified documents where x is greater then 5 by 1
var result = await collection.UpdateManyAsync(
Builders<BsonDocument>.Filter.Gt("x", 5),
Builders<BsonDocument>.Update.Inc("x", 1));
//Strongly Typed Alternative 1
var result = await collection.UpdateManyAsync(
Builders<Person>.Filter.Gt(x => x.X, 5),
Builders<BsonDocument>.Update.Inc(x => x.X, 1));
//Strongly Typed Alternative 2
var result = await collection.UpdateManyAsync(
x => x.X > 5, //This syntax is availabe for filters only
Builders<BsonDocument>.Update.Inc(x => x.X, 1).Set("Y", 20));
//Sets a new field on the document - //will be problems when we read to POCOs
------------------------------------------------------------------------------
//Delete
var collection = db.GetCollection<Widget>("widgets");
var result = await collection.DeleteOneAsync(x => x.X > 5);
var result = await collection.DeleteManyAsync(x => x.X > 5);
------------------------------------------------------------------------------
//FindAndUpdate - Same for FindAndDelete
var collection = db.GetCollection<Widget>("widgets");
//Returns the modified document before modification
var result = await collection.FindOneAndUpdateAsync(
x => x.X > 5,
Builders<Widget>.Update.Inc(x => x.X, 1));
var result = await collection.FindOneAndUpdateAsync<Widget>(
x => x.X > 5,
Builders<Widget>.Update.Inc(x => x.X, 1),
new FindOneAndUpdateOptions<Widget, Widget> //Second Widghet T parameter says what we wont to work with, we could enter a projection here
{
ReturnDocument = ReturnDocument.After, //Returns the document after modification
Sort = Builders<Widget>.Sort.Descending(x => x.X) //Takes the first document matching the filter and increments
});
--------------------------------------------------------------------------------
//BulkWriter
var collection = db.GetCollection<Widget>("widgets");
//Performs all operation in one turn to the database
var result = collection.BulkWriteAsync(new WriteModel<BsonDocument>[]
{
new DeleteOneModel<BsonDocument>("{x: 5}"),
new DeleteOneModel<BsonDocument>("{x: 7}"),
new UpdateManyModel<BsonDocument>("{x: {$lt: 7}}", {"$inc: {x: 1}}")
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment