Browse Source

Added primer examples.

pull/200/head
rstam 11 years ago
parent
commit
e7f0debb48
  1. 9
      src/CSharpDriver.sln
  2. 3
      src/MongoDB.Driver.Core/IAsyncCursorSource.cs
  3. 79
      src/MongoDB.Driver.Examples/AggregatePrimer.cs
  4. 23
      src/MongoDB.Driver.Examples/AltersCollectionAttribute.cs
  5. 67
      src/MongoDB.Driver.Examples/IndexesPrimer.cs
  6. 72
      src/MongoDB.Driver.Examples/InsertPrimer.cs
  7. 107
      src/MongoDB.Driver.Examples/MongoDB.Driver.Examples.csproj
  8. 85
      src/MongoDB.Driver.Examples/PrimerTestFixture.cs
  9. 35
      src/MongoDB.Driver.Examples/Properties/AssemblyInfo.cs
  10. 212
      src/MongoDB.Driver.Examples/QueryPrimer.cs
  11. 80
      src/MongoDB.Driver.Examples/RemovePrimer.cs
  12. 29
      src/MongoDB.Driver.Examples/SetupFixture.cs
  13. 90
      src/MongoDB.Driver.Examples/UpdatePrimer.cs
  14. 25359
      src/MongoDB.Driver.Examples/dataset.json
  15. 4
      src/MongoDB.Driver.Examples/packages.config

9
src/CSharpDriver.sln

@ -11,7 +11,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MongoDB.Driver", "MongoDB.D
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MongoDB.Driver.Tests", "MongoDB.Driver.Tests\MongoDB.Driver.Tests.csproj", "{FBBF0D71-107F-49C4-8858-B3A4DC24AA33}"
EndProject
Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "MongoDB.Driver.VB.Tests", "MongoDB.Driver.Legacy.VB.Tests\MongoDB.Driver.Legacy.VB.Tests.vbproj", "{19ED9AD5-A2CA-4F1B-9BE4-96450382F404}"
Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "MongoDB.Driver.Legacy.VB.Tests", "MongoDB.Driver.Legacy.VB.Tests\MongoDB.Driver.Legacy.VB.Tests.vbproj", "{19ED9AD5-A2CA-4F1B-9BE4-96450382F404}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MongoDB.Driver.Core", "MongoDB.Driver.Core\MongoDB.Driver.Core.csproj", "{DA56482A-5D8F-41E0-85E6-1F22B310F91B}"
EndProject
@ -41,6 +41,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Legacy", "Legacy", "{C0AC2F
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Misc", "Misc", "{391D831D-5AC7-43F8-8BCB-6AE81B027658}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MongoDB.Driver.Examples", "MongoDB.Driver.Examples\MongoDB.Driver.Examples.csproj", "{0B7600F4-A343-4007-8977-933DBEFC0CC7}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -103,6 +105,10 @@ Global
{02AB2E44-785A-4D39-99C0-29F93A02EF84}.Debug|Any CPU.Build.0 = Debug|Any CPU
{02AB2E44-785A-4D39-99C0-29F93A02EF84}.Release|Any CPU.ActiveCfg = Release|Any CPU
{02AB2E44-785A-4D39-99C0-29F93A02EF84}.Release|Any CPU.Build.0 = Release|Any CPU
{0B7600F4-A343-4007-8977-933DBEFC0CC7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0B7600F4-A343-4007-8977-933DBEFC0CC7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0B7600F4-A343-4007-8977-933DBEFC0CC7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0B7600F4-A343-4007-8977-933DBEFC0CC7}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@ -122,5 +128,6 @@ Global
{4F42BA31-AAA3-4BD4-A4F2-7F7A53940D69} = {C0AC2FCF-37FB-4A64-ACC6-8490DC15091D}
{89B92FFF-4126-4D9A-93C8-2BD7E0CD82FF} = {11282844-4584-4F65-9857-D4329046E84D}
{02AB2E44-785A-4D39-99C0-29F93A02EF84} = {C0AC2FCF-37FB-4A64-ACC6-8490DC15091D}
{0B7600F4-A343-4007-8977-933DBEFC0CC7} = {391D831D-5AC7-43F8-8BCB-6AE81B027658}
EndGlobalSection
EndGlobal

3
src/MongoDB.Driver.Core/IAsyncCursorSource.cs

@ -17,6 +17,7 @@ using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace MongoDB.Driver
{
/// <summary>
@ -30,7 +31,7 @@ namespace MongoDB.Driver
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>A Task whose result is a cursor.</returns>
Task<IAsyncCursor<TDocument>> ToCursorAsync(CancellationToken cancellationToken);
Task<IAsyncCursor<TDocument>> ToCursorAsync(CancellationToken cancellationToken = default(CancellationToken));
}
/// <summary>

79
src/MongoDB.Driver.Examples/AggregatePrimer.cs

@ -0,0 +1,79 @@
/* Copyright 2010-2015 MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Threading.Tasks;
using FluentAssertions;
using MongoDB.Bson;
using NUnit.Framework;
namespace MongoDB.Driver.Examples
{
[TestFixture]
public class AggregatePrimer : PrimerTestFixture
{
[Test]
public async Task GroupDocumentsByAFieldAndCalculateCount()
{
// @begin: group-documents-by-a-field-and-calculate-count
// @code: start
var collection = _database.GetCollection<BsonDocument>("restaurants");
var aggregate = collection.Aggregate().Group(new BsonDocument { { "_id", "$borough" }, { "count", new BsonDocument("$sum", 1) } });
var results = await aggregate.ToListAsync();
// @code: end
// @results: start
var expectedResults = new[]
{
BsonDocument.Parse("{ _id : 'Staten Island', count : 969 }"),
BsonDocument.Parse("{ _id : 'Brooklyn', count : 6086 }"),
BsonDocument.Parse("{ _id : 'Manhattan', count : 10259 }"),
BsonDocument.Parse("{ _id : 'Queens', count : 5656 }"),
BsonDocument.Parse("{ _id : 'Bronx', count : 2338 }"),
BsonDocument.Parse("{ _id : 'Missing', count : 51 }")
};
results.Should().BeEquivalentTo(expectedResults);
// @results: end
// @end: group-documents-by-a-field-and-calculate-count
}
[Test]
public async Task FilterAndGroupDocuments()
{
// @begin: filter-and-group-documents
// @code: start
var collection = _database.GetCollection<BsonDocument>("restaurants");
var aggregate = collection.Aggregate()
.Match(new BsonDocument { { "borough", "Queens" }, { "cuisine", "Brazilian" } })
.Group(new BsonDocument { { "_id", "$address.zipcode" }, { "count", new BsonDocument("$sum", 1) } });
var results = await aggregate.ToListAsync();
// @code: end
// @results: start
var expectedResults = new[]
{
BsonDocument.Parse("{ _id : '11368', count : 1 }"),
BsonDocument.Parse("{ _id : '11106', count : 3 }"),
BsonDocument.Parse("{ _id : '11377', count : 1 }"),
BsonDocument.Parse("{ _id : '11103', count : 1 }"),
BsonDocument.Parse("{ _id : '11101', count : 2 }")
};
results.Should().BeEquivalentTo(expectedResults);
// @results: end
// @end: filter-and-group-documents
}
}
}

23
src/MongoDB.Driver.Examples/AltersCollectionAttribute.cs

@ -0,0 +1,23 @@
/* Copyright 2010-2015 MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
namespace MongoDB.Driver.Examples
{
public class AltersCollectionAttribute : Attribute
{
}
}

67
src/MongoDB.Driver.Examples/IndexesPrimer.cs

@ -0,0 +1,67 @@
/* Copyright 2010-2015 MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Threading.Tasks;
using FluentAssertions;
using MongoDB.Bson;
using NUnit.Framework;
namespace MongoDB.Driver.Examples
{
[TestFixture]
public class IndexesPrimer : PrimerTestFixture
{
[Test]
[AltersCollection]
public async Task SingleFieldIndex()
{
// @begin: single-field-index
// @code: start
var collection = _database.GetCollection<BsonDocument>("restaurants");
var keys = Builders<BsonDocument>.IndexKeys.Ascending("cuisine");
await collection.Indexes.CreateAsync(keys);
// @code: end
// @results: start
var cursor = await collection.Indexes.ListAsync();
var indexes = await cursor.ToListAsync();
indexes.Should().Contain(index => index["name"] == "cuisine_1");
// @results: end
// @end: single-field-index
}
[Test]
[AltersCollection]
public async Task CreateCompoundIndex()
{
// @begin: create-compound-index
// @code: start
var collection = _database.GetCollection<BsonDocument>("restaurants");
var keys = Builders<BsonDocument>.IndexKeys.Ascending("cuisine").Ascending("address.zipcode");
await collection.Indexes.CreateAsync(keys);
// @code: end
// @results: start
var cursor = await collection.Indexes.ListAsync();
var indexes = await cursor.ToListAsync();
indexes.Should().Contain(index => index["name"] == "cuisine_1_address.zipcode_1");
// @results: end
// @end: create-compound-index
}
}
}

72
src/MongoDB.Driver.Examples/InsertPrimer.cs

@ -0,0 +1,72 @@
/* Copyright 2010-2015 MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Threading.Tasks;
using MongoDB.Bson;
using NUnit.Framework;
namespace MongoDB.Driver.Examples
{
[TestFixture]
public class InsertPrimer : PrimerTestFixture
{
[Test]
[AltersCollection]
public async Task InsertADocument()
{
// @begin: insert-a-document
// @code: start
var document = new BsonDocument
{
{ "address" , new BsonDocument
{
{ "street", "2 Avenue" },
{ "zipcode", "10075" },
{ "building", "1480" },
{ "coord", new BsonArray { 73.9557413, 40.7720266 } }
}
},
{ "borough", "Manhattan" },
{ "cuisine", "Italian" },
{ "grades", new BsonArray
{
new BsonDocument
{
{ "date", new DateTime(2014, 10, 1, 0, 0, 0, DateTimeKind.Utc) },
{ "grade", "A" },
{ "score", 11 }
},
new BsonDocument
{
{ "date", new DateTime(2014, 1, 6, 0, 0, 0, DateTimeKind.Utc) },
{ "grade", "B" },
{ "score", 17 }
}
}
},
{ "name", "Vella" },
{ "restaurant_id", "41704620" }
};
var collection = _database.GetCollection<BsonDocument>("restaurants");
await collection.InsertOneAsync(document);
// @code: end
// @post: The method does not return a result
// @end: insert-a-document
}
}
}

107
src/MongoDB.Driver.Examples/MongoDB.Driver.Examples.csproj

@ -0,0 +1,107 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{0B7600F4-A343-4007-8977-933DBEFC0CC7}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>MongoDB.Driver.Examples</RootNamespace>
<AssemblyName>MongoDB.Driver.Examples</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="FluentAssertions">
<HintPath>..\packages\FluentAssertions.3.2.1\lib\net45\FluentAssertions.dll</HintPath>
</Reference>
<Reference Include="FluentAssertions.Core, Version=3.2.1.0, Culture=neutral, PublicKeyToken=33f2691a05b67b6a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\FluentAssertions.3.2.1\lib\net45\FluentAssertions.Core.dll</HintPath>
</Reference>
<Reference Include="nunit.framework">
<HintPath>..\..\Tools\NUnit\nunit.framework.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="AggregatePrimer.cs" />
<Compile Include="AltersCollectionAttribute.cs" />
<Compile Include="IndexesPrimer.cs" />
<Compile Include="InsertPrimer.cs" />
<Compile Include="PrimerTestFixture.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="QueryPrimer.cs" />
<Compile Include="RemovePrimer.cs" />
<Compile Include="SetupFixture.cs" />
<Compile Include="UpdatePrimer.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\MongoDB.Bson.TestHelpers\MongoDB.Bson.TestHelpers.csproj">
<Project>{6ac4638e-ec69-46aa-b6aa-c5cf227d14ae}</Project>
<Name>MongoDB.Bson.TestHelpers</Name>
</ProjectReference>
<ProjectReference Include="..\MongoDB.Bson\MongoDB.Bson.csproj">
<Project>{0e9a3a2a-49cd-4f6c-847c-dc79b4b65ce6}</Project>
<Name>MongoDB.Bson</Name>
</ProjectReference>
<ProjectReference Include="..\MongoDB.Driver.Core.TestHelpers\MongoDB.Driver.Core.TestHelpers.csproj">
<Project>{26c8e1f2-d859-4ed0-a1a7-de0b32f81084}</Project>
<Name>MongoDB.Driver.Core.TestHelpers</Name>
</ProjectReference>
<ProjectReference Include="..\MongoDB.Driver.Core\MongoDB.Driver.Core.csproj">
<Project>{da56482a-5d8f-41e0-85e6-1f22b310f91b}</Project>
<Name>MongoDB.Driver.Core</Name>
</ProjectReference>
<ProjectReference Include="..\MongoDB.Driver.TestHelpers\MongoDB.Driver.TestHelpers.csproj">
<Project>{89b92fff-4126-4d9a-93c8-2bd7e0cd82ff}</Project>
<Name>MongoDB.Driver.TestHelpers</Name>
</ProjectReference>
<ProjectReference Include="..\MongoDB.Driver\MongoDB.Driver.csproj">
<Project>{ae5166cd-76b0-4911-bd80-ced9521f37a1}</Project>
<Name>MongoDB.Driver</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="dataset.json" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

85
src/MongoDB.Driver.Examples/PrimerTestFixture.cs

@ -0,0 +1,85 @@
/* Copyright 2010-2015 MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using MongoDB.Bson;
using NUnit.Framework;
namespace MongoDB.Driver.Examples
{
public class PrimerTestFixture
{
protected static IMongoClient _client;
protected static IMongoDatabase _database;
private static List<BsonDocument> _dataset;
[TestFixtureSetUp]
public void TestFixtureSetup()
{
var connectionString = CoreTestConfiguration.ConnectionString.ToString();
_client = new MongoClient(connectionString);
_database = _client.GetDatabase("test");
LoadDataSetFromResource();
LoadCollection();
}
[TearDown]
public void TearDown()
{
var methodName = TestContext.CurrentContext.Test.Name;
var methodInfo = GetType().GetMethod(methodName);
var altersCollectionAttribute = methodInfo.GetCustomAttribute(typeof(AltersCollectionAttribute));
if (altersCollectionAttribute != null)
{
LoadCollection();
}
}
// helper methods
private void LoadCollection()
{
LoadCollectionAsync().GetAwaiter().GetResult();
}
private async Task LoadCollectionAsync()
{
await _database.DropCollectionAsync("restaurants");
var collection = _database.GetCollection<BsonDocument>("restaurants");
await collection.InsertManyAsync(_dataset);
}
private void LoadDataSetFromResource()
{
_dataset = new List<BsonDocument>();
var assembly = Assembly.GetExecutingAssembly();
using (var stream = assembly.GetManifestResourceStream("MongoDB.Driver.Examples.dataset.json"))
using (var reader = new StreamReader(stream))
{
string line;
while ((line = reader.ReadLine()) != null)
{
var document = BsonDocument.Parse(line);
_dataset.Add(document);
}
}
}
}
}

35
src/MongoDB.Driver.Examples/Properties/AssemblyInfo.cs

@ -0,0 +1,35 @@
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MongoDB.Driver.Examples")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MongoDB.Driver.Examples")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("fb712c63-ff17-4d4a-a807-9630086e6233")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

212
src/MongoDB.Driver.Examples/QueryPrimer.cs

@ -0,0 +1,212 @@
/* Copyright 2010-2014 MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FluentAssertions;
using MongoDB.Bson;
using NUnit.Framework;
namespace MongoDB.Driver.Examples
{
[TestFixture]
public class QueryPrimer : PrimerTestFixture
{
[Test]
public async Task QueryAll()
{
// @begin: query-all
// @code: start
var collection = _database.GetCollection<BsonDocument>("restaurants");
var filter = new BsonDocument();
var result = await collection.Find(filter).ToListAsync();
// @code: end
// @results: start
result.Count().Should().Be(25359);
// @results: end
// @end: query-all
}
[Test]
public async Task LogicalAnd()
{
// @begin: logical-and
// @code: start
var collection = _database.GetCollection<BsonDocument>("restaurants");
var filter = Builders<BsonDocument>.Filter.And(
Builders<BsonDocument>.Filter.Eq("cuisine", "Italian"),
Builders<BsonDocument>.Filter.Eq("address.zipcode", "10075"));
var result = await collection.Find(filter).ToListAsync();
// @code: end
// @results: start
result.Count().Should().Be(15);
// @results: end
// @end: logical-and
}
[Test]
public async Task LogicalOr()
{
// @begin: logical-or
// @code: start
var collection = _database.GetCollection<BsonDocument>("restaurants");
var filter = Builders<BsonDocument>.Filter.Or(
Builders<BsonDocument>.Filter.Eq("cuisine", "Italian"),
Builders<BsonDocument>.Filter.Eq("address.zipcode", "10075"));
var result = await collection.Find(filter).ToListAsync();
// @code: end
// @results: start
result.Count().Should().Be(1153);
// @results: end
// @end: logical-or
}
[Test]
public async Task QueryTopLevelField()
{
// @begin: query-top-level-field
// @code: start
var collection = _database.GetCollection<BsonDocument>("restaurants");
var filter = Builders<BsonDocument>.Filter.Eq("borough", "Manhattan");
var result = await collection.Find(filter).ToListAsync();
// @code: end
// @results: start
result.Count().Should().Be(10259);
// @results: end
// @end: query-top-level-field
}
[Test]
public async Task QueryEmbeddedDocument()
{
// @begin: query-embedded-document
// @code: start
var collection = _database.GetCollection<BsonDocument>("restaurants");
var filter = Builders<BsonDocument>.Filter.Eq("address.zipcode", "10075");
var result = await collection.Find(filter).ToListAsync();
// @code: end
// @results: start
result.Count().Should().Be(99);
// @results: end
// @end: query-embedded-document
}
[Test]
public async Task QueryFieldInArray()
{
// @begin: query-field-in-array
// @code: start
var collection = _database.GetCollection<BsonDocument>("restaurants");
var filter = Builders<BsonDocument>.Filter.Eq("grades.grade", "B");
var result = await collection.Find(filter).ToListAsync();
// @code: end
// @results: start
result.Count().Should().Be(8280);
// @results: end
// @end: query-field-in-array
}
[Test]
public async Task GreaterThan()
{
// @begin: greater-than
// @code: start
var collection = _database.GetCollection<BsonDocument>("restaurants");
var filter = Builders<BsonDocument>.Filter.Gt("grades.score", 30);
var result = await collection.Find(filter).ToListAsync();
// @code: end
// @results: start
result.Count().Should().Be(1959);
// @results: end
// @end: greater-than
}
[Test]
public async Task LessThan()
{
// @begin: less-than
// @code: start
var collection = _database.GetCollection<BsonDocument>("restaurants");
var filter = Builders<BsonDocument>.Filter.Lt("grades.score", 10);
var result = await collection.Find(filter).ToListAsync();
// @code: end
// @results: start
result.Count().Should().Be(19065);
// @results: end
// @end: less-than
}
[Test]
public async Task Sort()
{
// @begin: sort
// @code: start
var collection = _database.GetCollection<BsonDocument>("restaurants");
var filter = new BsonDocument();
var sort = Builders<BsonDocument>.Sort.Ascending("borough").Ascending("address.zipcode");
var result = await collection.Find(filter).Sort(sort).ToListAsync();
// @code: end
// @results: start
Func<BsonDocument, BsonDocument> keyFunc = document => new BsonDocument { { "borough", document["borough"] }, { "address.zipcode", document.GetValue("address.zipcode", "") } };
IsInAscendingOrder(result, keyFunc).Should().BeTrue();
// @results: end
// @end: sort
}
// helper methods
private bool IsInAscendingOrder(List<BsonDocument> documents, Func<BsonDocument, BsonDocument> keyFunc)
{
BsonDocument previousKey = null;
foreach (var document in documents)
{
if (previousKey == null)
{
previousKey = keyFunc(document);
}
else
{
var key = keyFunc(document);
if (key < previousKey)
{
return false;
}
previousKey = key;
}
}
return true;
}
}
}

80
src/MongoDB.Driver.Examples/RemovePrimer.cs

@ -0,0 +1,80 @@
/* Copyright 2010-2014 MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Threading.Tasks;
using FluentAssertions;
using MongoDB.Bson;
using NUnit.Framework;
namespace MongoDB.Driver.Examples
{
[TestFixture]
public class RemovePrimer : PrimerTestFixture
{
[Test]
[AltersCollection]
public async Task RemoveMatchingDocument()
{
// @begin: remove-matching-documents
// @code: start
var collection = _database.GetCollection<BsonDocument>("restaurants");
var filter = Builders<BsonDocument>.Filter.Eq("borough", "Manhattan");
var result = await collection.DeleteManyAsync(filter);
// @code: end
// @results: start
result.DeletedCount.Should().Be(10259);
// @results: end
// @end: remove-matching-documents
}
[Test]
[AltersCollection]
public async Task RemoveAllDocuments()
{
// @begin: remove-all-documents
// @code: start
var collection = _database.GetCollection<BsonDocument>("restaurants");
var filter = new BsonDocument();
var result = await collection.DeleteManyAsync(filter);
// @code: end
// @results: start
result.DeletedCount.Should().Be(25359);
// @results: end
// @end: remove-all-documents
}
[Test]
[AltersCollection]
public async Task DropCollection()
{
// @begin: drop-collection
// @code: start
await _database.DropCollectionAsync("restaurants");
// @code: end
// @results: start
var cursor = await _database.ListCollectionsAsync();
var collections = await cursor.ToListAsync();
collections.Should().NotContain(document => document["name"] == "restaurants");
// @results: end
// @end: drop-collection
}
}
}

29
src/MongoDB.Driver.Examples/SetupFixture.cs

@ -0,0 +1,29 @@
/* Copyright 2010-2014 MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using NUnit.Framework;
namespace MongoDB.Driver.Examples
{
[SetUpFixture]
public class SetUpFixture
{
[TearDown]
public void TearDown()
{
CoreTestConfiguration.TearDown();
}
}
}

90
src/MongoDB.Driver.Examples/UpdatePrimer.cs

@ -0,0 +1,90 @@
/* Copyright 2010-2014 MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Threading.Tasks;
using FluentAssertions;
using MongoDB.Bson;
using MongoDB.Driver.Core;
using NUnit.Framework;
namespace MongoDB.Driver.Examples
{
[TestFixture]
public class UpdatePrimer : PrimerTestFixture
{
[Test]
[AltersCollection]
[RequiresServer(MinimumVersion = "2.6.0")]
public async Task UpdateTopLevelFields()
{
// @begin: update-top-level-fields
// @code: start
var collection = _database.GetCollection<BsonDocument>("restaurants");
var filter = Builders<BsonDocument>.Filter.Eq("name", "Juni");
var update = Builders<BsonDocument>.Update
.Set("cuisine", "American (New)")
.CurrentDate("lastModified");
var result = await collection.UpdateOneAsync(filter, update);
// @code: end
// @results: start
result.ModifiedCount.Should().Be(1);
// @results: end
// @end: update-top-level-fields
}
[Test]
[AltersCollection]
public async Task UpdateEmbeddedField()
{
// @begin: update-embedded-field
// @code: start
var collection = _database.GetCollection<BsonDocument>("restaurants");
var filter = Builders<BsonDocument>.Filter.Eq("restaurant_id", "41156888");
var update = Builders<BsonDocument>.Update.Set("address.street", "East 31st Street");
var result = await collection.UpdateOneAsync(filter, update);
// @code: end
// @results: start
result.ModifiedCount.Should().Be(1);
// @results: end
// @end: update-embedded-field
}
[Test]
[AltersCollection]
public async Task UpdateMultipleDocuments()
{
// @begin: update-multiple-documents
// @code: start
var collection = _database.GetCollection<BsonDocument>("restaurants");
var filter = Builders<BsonDocument>.Filter.Eq("address.zipcode", "10016");
var update = Builders<BsonDocument>.Update
.Set("borough", "Midtown")
.CurrentDate("lastModified");
var result = await collection.UpdateManyAsync(filter, update);
// @code: end
// @results: start
result.MatchedCount.Should().Be(433);
result.ModifiedCount.Should().Be(433);
// @results: end
// @end: update-multiple-documents
}
}
}

25359
src/MongoDB.Driver.Examples/dataset.json
File diff suppressed because it is too large
View File

4
src/MongoDB.Driver.Examples/packages.config

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="FluentAssertions" version="3.2.1" targetFramework="net45" />
</packages>
Loading…
Cancel
Save