MongoDB Driver Quick Tour(C#)

http://mongodb.github.io/mongo-csharp-driver/2.0/getting_started/quick_tour/

Make a connection


// To directly connect to a single MongoDB server
// (this will not auto-discover the primary even if it's a member of a replica set)
var client = new MongoClient();

// or use a connection string
var client = new MongoClient("mongodb://localhost:27017");

// or, to connect to a replica set, with auto-discovery of the primary, supply a seed list of members
var client = new MongoClient("mongodb://localhost:27017,localhost:27018,localhost:27019");

Get a Database

var database = client.GetDatabase("foo");

Get a Collection

var collection = database.GetCollection<BsonDocument>("bar");

 

Insert a Document

var doc= new BsonDocument { { "name", "MongoDB" }, { "type", "Database" }, { "count", 1 }, { "info", new BsonDocument { { "x", 203 }, { "y", 102 } }} };

await collection.InsertOneAsync(doc);

Insert Multiple Documents

// generate 100 documents with a counter ranging from 0 - 99

var documents = Enumerable.Range(0, 100).Select(i => new BsonDocument("counter", i));

await collection.InsertManyAsync(documents);

 

Counting Documents

var count = await collection.CountAsync(new BsonDocument());

Console.WriteLine(count);

Find the First Document in a Collection

var document = await collection.Find(new BsonDocument()).FirstOrDefaultAsync(); Console.WriteLine(document.ToString());

 

Find All Documents in a Collection

var documents = await collection.Find(new BsonDocument()).ToListAsync();

--If the number of documents is expected to be large or they can be processed iteratively, the ForEachAsyncwill invoke a callback for each document returned.

await collection.Find(new BsonDocument()).ForEachAsync(d => Console.WriteLine(d));

Get a Single Document with a Filter

var filter = Builders<BsonDocument>.Filter.Eq("i", 71);

var document = await collection.Find(filter).FirstAsync();

Console.WriteLine(document);

 

Get a Set of Documents with a Filter

var filter = Builders<BsonDocument>.Filter.Gt("i", 50);

await collection.Find(filter).ForEachAsync(d => Console.WriteLine(d));

 

--We could also get a range, say 50 < i <= 100:

var filterBuilder = Builders<BsonDocument>.Filter;
var filter = filterBuilder.Gt("i", 50) & filterBuilder.Lte("i", 100);

await collection.Find(filter).ForEachAsync(d => Console.WriteLine(d));

Sorting Documents

We add a sort to a find query by calling the Sort method. Below we use the Exists filter builder method and Descending sort builder method to sort our documents:

var filter = Builders<BsonDocument>.Filter.Exists("i");
var sort = Builders<BsonDocument>.Sort.Descending("i");

var document = await collection.Find(filter).Sort(sort).FirstAsync();

Updating Documents

There are numerous update operators supported by MongoDB.

To update at most 1 document (may be 0 if none match the filter), use the UpdateOneAsync method to specify the filter and the update document. Here we update the first document that meets the filter i == 10and set the value of i to 110:

var filter = Builders<BsonDocument>.Filter.Eq("i", 10);
var update = Builders<BsonDocument>.Update.Set("i", 110);

await collection.UpdateOneAsync(filter, update);

To update all documents matching the filter use the UpdateManyAsync method. Here we increment the value of i by 100 where i < 100.

var filter = Builders<BsonDocument>.Filter.Lt("i", 100);
var update = Builders<BsonDocument>.Update.Inc("i", 100);

var result = await collection.UpdateOneAsync(filter, update);

if (result.IsModifiedCountAvailable)
{
    Console.WriteLine(result.ModifiedCount);
}

The update methods return an UpdateResult which provides information about the operation including the number of documents modified by the update.

Deleting Documents

To delete at most 1 document (may be 0 if none match the filter) use the DeleteOneAsync method:

var filter = Builders<BsonDocument>.Filter.Eq("i", 110));

await collection.DeleteOneAsync(filter);

To delete all documents matching the filter use the DeleteManyAsync method method. Here we delete all documents where i >= 100:

var filter = Builders<BsonDocument>.Filter.Gte("i", 100));

var result = await collection.DeleteManyAsync(filter);

Console.WriteLine(result.DeletedCount);

The delete methods return a DeleteResult which provides information about the operation including the number of documents deleted.

Bulk Writes

There are two types of bulk operations:

  1. Ordered bulk operations.

    Executes all the operations in order and errors out on the first error.

  2. Unordered bulk operations.

    Executes all the operations and reports any errors. Unordered bulk operations do not guarantee the order of execution.

Let’s look at two simple examples using ordered and unordered operations:


var models = new WriteModel<BsonDocument>[] 
{
    new InsertOneModel<BsonDocument>(new BsonDocument("_id", 4)),
    new InsertOneModel<BsonDocument>(new BsonDocument("_id", 5)),
    new InsertOneModel<BsonDocument>(new BsonDocument("_id", 6)),
    new UpdateOneModel<BsonDocument>(
        new BsonDocument("_id", 1), 
        new BsonDocument("$set", new BsonDocument("x", 2))),
    new DeleteOneModel<BsonDocument>(new BsonDocument("_id", 3)),
    new ReplaceOneModel<BsonDocument>(
        new BsonDocument("_id", 3), 
        new BsonDocument("_id", 3).Add("x", 4))
};

// 1. Ordered bulk operation - order of operation is guaranteed
await collection.BulkWrite(models);

// 2. Unordered bulk operation - no guarantee of order of operation
await collection.BulkWrite(models, new BulkWriteOptions { IsOrdered = false });


 

posted on 2016-04-10 19:03  踏歌&而行  阅读(577)  评论(0)    收藏  举报