Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Huge change. Refectored Collections to use generics but append still …

…Document overloads to show the user that he also can pass Documents here.
  • Loading branch information...
commit b6d2bd9cf0da7c90e80b3ab98d46d83b1a728a08 1 parent d0d0779
@lanwin lanwin authored
View
12 MongoDB.GridFS/GridFile.cs
@@ -12,14 +12,16 @@ public class GridFile{
public string Name {
get { return name; }
}
-
- private IMongoCollection files;
- public IMongoCollection Files{
+
+ private IMongoCollection<Document> files;
+ public IMongoCollection<Document> Files
+ {
get { return this.files; }
}
- private IMongoCollection chunks;
- public IMongoCollection Chunks{
+ private IMongoCollection<Document> chunks;
+ public IMongoCollection<Document> Chunks
+ {
get { return this.chunks; }
}
View
11 MongoDB.GridFS/GridFileStream.cs
@@ -16,9 +16,9 @@ namespace MongoDB.GridFS
/// </remarks>
public class GridFileStream : Stream
{
-
- private IMongoCollection files;
- private IMongoCollection chunks;
+
+ private IMongoCollection<Document> files;
+ private IMongoCollection<Document> chunks;
private Document chunk;
private bool chunkDirty;
private long chunkLower = -1;
@@ -68,8 +68,9 @@ public class GridFileStream : Stream
}
}
#endregion
-
- public GridFileStream(GridFileInfo gridfileinfo,IMongoCollection files, IMongoCollection chunks, FileAccess access){
+
+ public GridFileStream(GridFileInfo gridfileinfo, IMongoCollection<Document> files, IMongoCollection<Document> chunks, FileAccess access)
+ {
switch (access){
case FileAccess.Read:
canRead = true;
View
4 MongoDB.Linq.Tests/TestMongoDocumentQuerySyntax.cs
@@ -11,13 +11,13 @@ namespace MongoDB.Linq.Tests {
public class TestMongoDocumentQuerySyntax {
private IMongoQuery queryable;
- private Mock<IMongoCollection> collectionMock;
+ private Mock<IMongoCollection<Document>> collectionMock;
private Mock<ICursor<Document>> cursorMock;
[SetUp]
public void Setup() {
Debug.WriteLine("initializing queryable");
- collectionMock = new Mock<IMongoCollection>();
+ collectionMock = new Mock<IMongoCollection<Document>>();
cursorMock = new Mock<ICursor<Document>>();
collectionMock.Setup(c => c.Find(It.IsAny<Document>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<Document>())).Returns(cursorMock.Object);
queryable = new MongoQuery(new MongoQueryProvider(collectionMock.Object));
View
4 MongoDB.Linq.Tests/TestQueryParsing.cs
@@ -11,13 +11,13 @@ namespace MongoDB.Linq.Tests {
public class TestQueryParsing {
private IMongoQuery queryable;
- private Mock<IMongoCollection> collectionMock;
+ private Mock<IMongoCollection<Document>> collectionMock;
private Mock<ICursor<Document>> cursorMock;
[SetUp]
public void Setup() {
Debug.WriteLine("initializing queryable");
- collectionMock = new Mock<IMongoCollection>();
+ collectionMock = new Mock<IMongoCollection<Document>>();
cursorMock = new Mock<ICursor<Document>>();
collectionMock.Setup(c => c.Find(It.IsAny<Document>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<Document>())).Returns(cursorMock.Object);
queryable = new MongoQuery(new MongoQueryProvider(collectionMock.Object));
View
2  MongoDB.Linq/MongoLinqEx.cs
@@ -5,7 +5,7 @@ namespace MongoDB.Linq
{
public static class MongoLinqEx
{
- public static IMongoQuery AsQueryable<T>(this T collection) where T : IMongoCollection
+ public static IMongoQuery AsQueryable<T>(this T collection) where T : IMongoCollection<Document>
{
return new MongoQuery(new MongoQueryProvider(collection));
}
View
5 MongoDB.Linq/MongoQueryProvider.cs
@@ -13,9 +13,10 @@ private struct Result {
public bool IsFirstCall;
}
- private readonly IMongoCollection collection;
+ private readonly IMongoCollection<Document> collection;
- public MongoQueryProvider(IMongoCollection collection) {
+ public MongoQueryProvider(IMongoCollection<Document> collection)
+ {
this.collection = collection;
}
View
30 MongoDB.Net-Tests/TestCollection.cs
@@ -16,14 +16,14 @@ public class TestCollection : MongoTestBase
}
public override void OnInit (){
- IMongoCollection finds = DB["finds"];
+ IMongoCollection<Document> finds = DB["finds"];
for(int j = 1; j < 100; j++){
finds.Insert(new Document(){{"x", 4},{"h", "hi"},{"j", j}});
}
for(int j = 100; j < 105; j++){
finds.Insert(new Document(){{"x", 4},{"n", 1},{"j", j}});
}
- IMongoCollection charreads = DB["charreads"];
+ IMongoCollection<Document> charreads = DB["charreads"];
charreads.Insert(new Document(){{"test", "1234" + pound + "56"}});
}
@@ -95,7 +95,7 @@ public class TestCollection : MongoTestBase
}
[Test]
public void TestFindWhereEquivalency(){
- IMongoCollection col = DB["finds"];
+ IMongoCollection<Document> col = DB["finds"];
Document lt = new Document().Append("j", new Document().Append("$lt", 5));
string where = "this.j < 5";
Document explicitWhere = new Document().Append("$where", new Code(where));
@@ -137,7 +137,7 @@ private int CountDocs(ICursor<Document> cur)
[Test]
public void TestSimpleInsert(){
- IMongoCollection inserts = DB["inserts"];
+ IMongoCollection<Document> inserts = DB["inserts"];
Document indoc = new Document();
indoc["song"] = "Palmdale";
indoc["artist"] = "Afroman";
@@ -152,7 +152,7 @@ private int CountDocs(ICursor<Document> cur)
[Test]
public void TestReallySimpleInsert(){
- IMongoCollection inserts = DB["inserts"];
+ IMongoCollection<Document> inserts = DB["inserts"];
Document indoc = new Document();
indoc["y"] = 1;
indoc["x"] = 2;
@@ -165,7 +165,7 @@ private int CountDocs(ICursor<Document> cur)
[Test]
public void TestPoundSymbolInsert(){
- IMongoCollection inserts = DB["inserts"];
+ IMongoCollection<Document> inserts = DB["inserts"];
Document indoc = new Document().Append("x","1234" + pound + "56").Append("y",1);;
inserts.Insert(indoc);
@@ -176,7 +176,7 @@ private int CountDocs(ICursor<Document> cur)
[Test]
public void TestArrayInsert(){
- IMongoCollection inserts = DB["inserts"];
+ IMongoCollection<Document> inserts = DB["inserts"];
Document indoc1 = new Document();
indoc1["song"] = "The Axe";
indoc1["artist"] = "Tinsley Ellis";
@@ -201,7 +201,7 @@ private int CountDocs(ICursor<Document> cur)
[Test]
public void TestInsertOfArray(){
OidGenerator ogen = new OidGenerator();
- IMongoCollection inserts = DB["inserts"];
+ IMongoCollection<Document> inserts = DB["inserts"];
Document album = new Document();
album["_id"] = ogen.Generate();
album["artist"] = "Popa Chubby";
@@ -223,7 +223,7 @@ private int CountDocs(ICursor<Document> cur)
[Test]
public void TestDelete(){
- IMongoCollection deletes = DB["deletes"];
+ IMongoCollection<Document> deletes = DB["deletes"];
Document doc = new Document();
doc["y"] = 1;
doc["x"] = 2;
@@ -243,7 +243,7 @@ private int CountDocs(ICursor<Document> cur)
[Test]
public void TestUpdateUpsertNotExisting(){
- IMongoCollection updates = DB["updates"];
+ IMongoCollection<Document> updates = DB["updates"];
Document doc = new Document();
doc["First"] = "Sam";
doc["Last"] = "CorderNE";
@@ -257,7 +257,7 @@ private int CountDocs(ICursor<Document> cur)
[Test]
public void TestUpdateUpsertExisting(){
- IMongoCollection updates = DB["updates"];
+ IMongoCollection<Document> updates = DB["updates"];
Document doc = new Document();
doc["First"] = "Mtt";
doc["Last"] = "Brewer";
@@ -281,7 +281,7 @@ private int CountDocs(ICursor<Document> cur)
[Test]
public void TestUpdateMany(){
- IMongoCollection updates = DB["updates"];
+ IMongoCollection<Document> updates = DB["updates"];
updates.Insert(new Document().Append("Last", "Cordr").Append("First","Sam"));
updates.Insert(new Document().Append("Last", "Cordr").Append("First","Sam2"));
@@ -316,7 +316,7 @@ private int CountDocs(ICursor<Document> cur)
[Test]
public void TestCount(){
- IMongoCollection counts = DB["counts"];
+ IMongoCollection<Document> counts = DB["counts"];
int top = 100;
for(int i = 0; i < top; i++){
counts.Insert(new Document().Append("Last", "Cordr").Append("First","Sam").Append("cnt", i));
@@ -327,7 +327,7 @@ private int CountDocs(ICursor<Document> cur)
[Test]
public void TestCountWithSpec(){
- IMongoCollection counts = DB["counts_spec"];
+ IMongoCollection<Document> counts = DB["counts_spec"];
counts.Insert(new Document().Append("Last", "Cordr").Append("First","Sam").Append("cnt", 1));
counts.Insert(new Document().Append("Last", "Cordr").Append("First","Sam").Append("cnt", 2));
counts.Insert(new Document().Append("Last", "Corder").Append("First","Sam").Append("cnt", 3));
@@ -340,7 +340,7 @@ private int CountDocs(ICursor<Document> cur)
[Test]
public void TestCountInvalidCollection(){
- IMongoCollection counts = DB["counts_wtf"];
+ IMongoCollection<Document> counts = DB["counts_wtf"];
Assert.AreEqual(0, counts.Count());
}
}
View
4 MongoDB.Net-Tests/TestCollectionMetaData.cs
@@ -17,8 +17,8 @@ public class TestCollectionMetaData : MongoTestBase
}
}
- public override void OnInit (){
- IMongoCollection its = DB["indextests"];
+ public override void OnInit (){
+ IMongoCollection<Document> its = DB["indextests"];
its.Insert(createDoc("S","A","Anderson","OH"));
its.Insert(createDoc("T","B","Delhi","OH"));
its.Insert(createDoc("F","B","Cincinnati","OH"));
View
21 MongoDB.Net-Tests/TestCollectionSafeMode.cs
@@ -17,8 +17,8 @@ public class TestCollectionSafeMode : MongoTestBase
[Test]
- public void TestBadInsert(){
- IMongoCollection col = InitCollection("safeinsert");
+ public void TestBadInsert(){
+ IMongoCollection<Document> col = InitCollection("safeinsert");
bool thrown = false;
try{
col.Insert(new Document {{"x",1},{"y",2}},true);
@@ -31,8 +31,8 @@ public class TestCollectionSafeMode : MongoTestBase
}
[Test]
- public void TestBadUpdate(){
- IMongoCollection col = InitCollection("safeupdate");
+ public void TestBadUpdate(){
+ IMongoCollection<Document> col = InitCollection("safeupdate");
bool thrown = false;
try{
col.Update(new Document {{"x", 1}}, new Document{{"x",2}},true);
@@ -48,8 +48,8 @@ public class TestCollectionSafeMode : MongoTestBase
}
[Test]
- public void TestMultiUpdate(){
- IMongoCollection col = InitCollection("safemupdate");
+ public void TestMultiUpdate(){
+ IMongoCollection<Document> col = InitCollection("safemupdate");
Document newy = new Document(){{"y", 2}};
col.UpdateAll(newy, new Document(){{"y",1}},true);
Assert.AreEqual(5, col.Count(newy));
@@ -66,10 +66,11 @@ public class TestCollectionSafeMode : MongoTestBase
Assert.Fail(String.Format("Wrong exception thrown: {0}", e.GetType().Name));
}
Assert.IsTrue(thrown, "Exception not thrown.");
- }
-
- protected IMongoCollection InitCollection(string name){
- IMongoCollection col = DB[name];
+ }
+
+ protected IMongoCollection<Document> InitCollection(string name)
+ {
+ IMongoCollection<Document> col = DB[name];
col.MetaData.CreateIndex(new Document{{"x", IndexOrder.Ascending}}, true);
for(int x = 0; x < 5; x++){
col.Insert(new Document{{"x", x}, {"y", 1}});
View
20 MongoDB.Net-Tests/TestConcurrency.cs
@@ -32,9 +32,9 @@ public class TestConcurrency :MongoTestBase
//[Test]
public void TestMultiThreadedWrites (){
Mongo db = new Mongo();
- db.Connect();
-
- IMongoCollection col = DB["threadinserts"];
+ db.Connect();
+
+ IMongoCollection<Document> col = DB["threadinserts"];
List<string> identifiers = new List<string>{"A", "B", "C", "D"};
List<Thread> threads = new List<Thread>();
@@ -89,9 +89,9 @@ public class TestConcurrency :MongoTestBase
[Test]
public void TestMultiThreadedReadsAndWrites(){
Mongo db = new Mongo();
- db.Connect();
-
- IMongoCollection col = DB["threadreadinserts"];
+ db.Connect();
+
+ IMongoCollection<Document> col = DB["threadreadinserts"];
List<string> identifiers = new List<string>{"A", "B", "C", "D"};
List<string> colnames = new List<string>{"threadsmallreads", "threadsmallreads",
@@ -146,8 +146,8 @@ public class TestConcurrency :MongoTestBase
public class Inserter{
public int Iterations{get; set;}
public int Count{get;set;}
- public String Identifier{get; set;}
- public IMongoCollection Collection{get; set;}
+ public String Identifier{get; set;}
+ public IMongoCollection<Document> Collection { get; set; }
public void DoInserts(){
for(int x = 0; x < this.Iterations; x++){
@@ -164,8 +164,8 @@ public class Inserter{
public class Reader{
public int Iterations{get; set;}
- public int Count{get;set;}
- public IMongoCollection Collection{get; set;}
+ public int Count{get;set;}
+ public IMongoCollection<Document> Collection { get; set; }
public void DoReads(){
for(int x = 0; x < this.Iterations; x++){
View
10 MongoDB.Net-Tests/TestCursor.cs
@@ -18,13 +18,13 @@ public class TestCursor : MongoTestBase
public override void OnInit (){
//smallreads
- IMongoCollection smallreads = DB["smallreads"];
+ IMongoCollection<Document> smallreads = DB["smallreads"];
for(int j = 1; j < 5; j++){
smallreads.Insert(new Document(){{"x", 4},{"j", j}});
}
smallreads.Insert(new Document(){{"x", 4}, {"j", 5}, {"n", 1}});
-
- IMongoCollection reads = DB["reads"];
+
+ IMongoCollection<Document> reads = DB["reads"];
for(int j = 1; j < 10000; j++){
reads.Insert(new Document(){{"x", 4},{"h", "hi"},{"j", j}});
}
@@ -95,7 +95,7 @@ public void TestCanReadAndKillCursor()
[Test]
public void TestSort(){
- IMongoCollection sorts = DB["sorts"];
+ IMongoCollection<Document> sorts = DB["sorts"];
int[] randoms = new int[]{4,6,8,9,1,3,2,5,7,0};
foreach(int x in randoms){
sorts.Insert(new Document().Append("x", randoms[x]));
@@ -125,7 +125,7 @@ public void TestCanReadAndKillCursor()
[Test]
public void TestHint(){
- IMongoCollection reads = DB["reads"];
+ IMongoCollection<Document> reads = DB["reads"];
Document hint = new Document().Append("x",IndexOrder.Ascending);
Document exp = reads.FindAll().Hint(hint).Explain();
View
8 MongoDB.Net-Tests/TestDatabase.cs
@@ -15,7 +15,7 @@ public class TestDatabase : MongoTestBase
[Test]
public void TestFollowReference(){
- IMongoCollection refs = DB["refs"];
+ IMongoCollection<Document> refs = DB["refs"];
Oid id = new Oid("4a7067c30a57000000008ecb");
string msg = "this has an oid key";
Document doc = new Document(){{"_id", id},{"msg", msg}};
@@ -40,7 +40,7 @@ public class TestDatabase : MongoTestBase
[Test]
public void TestReferenceNonOid(){
- IMongoCollection refs = DB["refs"];
+ IMongoCollection<Document> refs = DB["refs"];
Document doc = new Document().Append("_id",123).Append("msg", "this has a non oid key");
refs.Insert(doc);
@@ -96,7 +96,7 @@ public class TestDatabase : MongoTestBase
[Test]
public void TestGetLastError(){
- IMongoCollection errcol = DB["errcol"];
+ IMongoCollection<Document> errcol = DB["errcol"];
errcol.MetaData.CreateIndex(new Document(){{"x", IndexOrder.Ascending}}, true);
Document dup = new Document(){{"x",1},{"y",2}};
errcol.Insert(dup);
@@ -112,7 +112,7 @@ public class TestDatabase : MongoTestBase
[Test]
public void TestGetPrevError(){
- IMongoCollection col = DB["preverror"];
+ IMongoCollection<Document> col = DB["preverror"];
col.MetaData.CreateIndex(new Document(){{"x", IndexOrder.Ascending}},true);
List<Document> docs = new List<Document>();
for(int x = 0; x < 10; x++){
View
8 MongoDB.Net-Tests/TestDatabaseJS.cs
@@ -18,9 +18,9 @@ public class TestDatabaseJS : MongoTestBase
public override void OnInit (){
DB["system.js"].Delete(new Document());
- js = DB.JS;
-
- IMongoCollection jsreads = DB["jsreads"];
+ js = DB.Javascript;
+
+ IMongoCollection<Document> jsreads = DB["jsreads"];
for(int j = 1; j < 10; j++){
jsreads.Insert(new Document(){{"j", j}});
}
@@ -28,7 +28,7 @@ public class TestDatabaseJS : MongoTestBase
[Test()]
public void TestCanGetDatabaseJSObject(){
- Assert.IsNotNull(DB.JS);
+ Assert.IsNotNull(DB.Javascript);
}
[Test()]
View
4 MongoDB.Net-Tests/TestMapReduce.cs
@@ -6,8 +6,8 @@ namespace MongoDB.Driver
{
[TestFixture()]
public class TestMapReduce : MongoTestBase
- {
- IMongoCollection mrcol;
+ {
+ IMongoCollection<Document> mrcol;
string mapfunction = "function(){\n" +
" this.tags.forEach(\n" +
" function(z){\n" +
View
4 MongoDB.Net-Tests/TestMapReduceBuilder.cs
@@ -8,8 +8,8 @@ namespace MongoDB.Driver
{
[TestFixture()]
public class TestMapReduceBuilder : MongoTestBase
- {
- IMongoCollection mrcol;
+ {
+ IMongoCollection<Document> mrcol;
string mapfunction = "function(){\n" +
" this.tags.forEach(\n" +
" function(z){\n" +
View
2  MongoDBDriver/Cursor.cs
@@ -40,7 +40,7 @@ public class Cursor<T> : ICursor<T>
/// <param name = "limit">The limit.</param>
/// <param name = "skip">The skip.</param>
/// <param name = "fields">The fields.</param>
- public Cursor(Connection connection, String fullCollectionName, Document spec, int limit, int skip, Document fields)
+ public Cursor(Connection connection, string fullCollectionName, object spec, int limit, int skip, object fields)
: this(connection, fullCollectionName){
//Todo: should be internal
if(spec == null)
View
230 MongoDBDriver/Database.cs
@@ -8,47 +8,76 @@ namespace MongoDB.Driver
{
public class Database
{
- private Connection connection;
- private IMongoCollection command;
+ private readonly IMongoCollection<Document> _command;
+ private readonly Connection _connection;
+ private DatabaseJS _javascript;
+ private DatabaseMetaData _metaData;
- public Database(string connectionString, String name){
- this.connection = ConnectionFactory.GetConnection(connectionString);
- this.Name = name;
- this.command = this["$cmd"];
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Database"/> class.
+ /// </summary>
+ /// <param name="connectionString">The connection string.</param>
+ /// <param name="name">The name.</param>
+ public Database(string connectionString, String name)
+ :this(ConnectionFactory.GetConnection(connectionString),name)
+ {
+ if(name == null)
+ throw new ArgumentNullException("name");
}
- public Database(Connection conn, String name){
- this.connection = conn;
- this.Name = name;
- this.command = this["$cmd"];
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Database"/> class.
+ /// </summary>
+ /// <param name="connection">The conn.</param>
+ /// <param name="name">The name.</param>
+ public Database(Connection connection, String name){
+ //Todo: should be internal
+ Name = name;
+ _connection = connection;
+ _command = this["$cmd"];
}
+ /// <summary>
+ /// Gets or sets the name.
+ /// </summary>
+ /// <value>The name.</value>
public string Name { get; private set; }
- private DatabaseMetaData metaData;
- public DatabaseMetaData MetaData {
- get { return metaData ?? (metaData = new DatabaseMetaData(this.Name, this.connection)); }
+ /// <summary>
+ /// Gets the meta data.
+ /// </summary>
+ /// <value>The meta data.</value>
+ public DatabaseMetaData MetaData{
+ get { return _metaData ?? (_metaData = new DatabaseMetaData(Name, _connection)); }
}
- private DatabaseJS js;
- public DatabaseJS JS {
- get { return js ?? (js = new DatabaseJS(this)); }
+ /// <summary>
+ /// Gets the javascript.
+ /// </summary>
+ /// <value>The javascript.</value>
+ public DatabaseJS Javascript{
+ get { return _javascript ?? (_javascript = new DatabaseJS(this)); }
}
- public List<String> GetCollectionNames(){
- IMongoCollection namespaces = this["system.namespaces"];
- ICursor<Document> cursor = namespaces.Find(new Document());
- List<String> names = new List<string>();
- foreach (Document doc in cursor.Documents){
- names.Add((String)doc["name"]); //Fix Me: Should filter built-ins
- }
- return names;
+ /// <summary>
+ /// Gets the <see cref="MongoDB.Driver.IMongoCollection&lt;MongoDB.Driver.Document&gt;"/> with the specified name.
+ /// </summary>
+ /// <value></value>
+ public IMongoCollection<Document> this[String name]{
+ get { return GetCollection(name); }
}
- public IMongoCollection this[ String name ] {
- get{
- return this.GetCollection(name);
- }
+ /// <summary>
+ /// Gets the collection names.
+ /// </summary>
+ /// <returns></returns>
+ public List<String> GetCollectionNames(){
+ var namespaces = this["system.namespaces"];
+ var cursor = namespaces.Find(new Document());
+ var names = new List<string>();
+ foreach(var document in cursor.Documents)
+ names.Add((String)document["name"]); //Todo: Should filter built-ins
+ return names;
}
/// <summary>
@@ -56,8 +85,8 @@ public class Database
/// </summary>
/// <param name="name">The name.</param>
/// <returns></returns>
- public IMongoCollection GetCollection(String name){
- return new MongoCollection<Document>(this.connection, this.Name, name);
+ public IMongoCollection<Document> GetCollection(String name){
+ return new MongoCollection<Document>(_connection, Name, name);
}
/// <summary>
@@ -67,115 +96,161 @@ public class Database
/// <param name="name">The name.</param>
/// <returns></returns>
public IMongoCollection<T> GetCollection<T>(String name) where T : class{
- return new MongoCollection<T>(this.connection, this.Name, name);
+ return new MongoCollection<T>(_connection, Name, name);
}
/// <summary>
/// Gets the document that a reference is pointing to.
/// </summary>
+ /// <param name="reference">The reference.</param>
+ /// <returns></returns>
public Document FollowReference(DBRef reference){
if(reference == null)
throw new ArgumentNullException("reference", "cannot be null");
- Document query = new Document().Append("_id", reference.Id);
+ var query = new Document().Append("_id", reference.Id);
return this[reference.CollectionName].FindOne(query);
}
-
+
/// <summary>
- /// Most operations do not have a return code in order to save the client from having to wait for results.
- /// GetLastError can be called to retrieve the return code if clients want one.
+ /// Follows the reference.
+ /// </summary>
+ /// <typeparam name="T"></typeparam>
+ /// <param name="reference">The reference.</param>
+ /// <returns></returns>
+ public T FollowReference<T>(DBRef reference) where T:class
+ {
+ if(reference == null)
+ throw new ArgumentNullException("reference", "cannot be null");
+ var query = new Document().Append("_id", reference.Id);
+ return GetCollection<T>(reference.CollectionName).FindOne(query);
+ }
+
+ /// <summary>
+ /// Most operations do not have a return code in order to save the client from having to wait for results.
+ /// GetLastError can be called to retrieve the return code if clients want one.
/// </summary>
public Document GetLastError(){
return SendCommand("getlasterror");
}
-
+
/// <summary>
- /// Retrieves the last error and forces the database to fsync all files before returning.
+ /// Retrieves the last error and forces the database to fsync all files before returning.
/// </summary>
- /// <remarks>Server version 1.3+</remarks>
+ /// <remarks>
+ /// Server version 1.3+
+ /// </remarks>
public Document GetLastErrorAndFSync(){
- return SendCommand(new Document {{"getlasterror", 1.0},{"fsync", true}});
+ return SendCommand(new Document{{"getlasterror", 1.0}, {"fsync", true}});
}
-
+
/// <summary>
- /// Call after sending a bulk operation to the database.
+ /// Call after sending a bulk operation to the database.
/// </summary>
public Document GetPreviousError(){
return SendCommand("getpreverror");
}
/// <summary>
- /// Gets the sister database on the same Mongo connection with the given name.
+ /// Gets the sister database on the same Mongo connection with the given name.
/// </summary>
public Database GetSisterDatabase(string sisterDbName){
- return new Database(connection, sisterDbName);
+ return new Database(_connection, sisterDbName);
}
-
+
/// <summary>
- /// Resets last error. This is good to call before a bulk operation.
+ /// Resets last error. This is good to call before a bulk operation.
/// </summary>
public void ResetError(){
- SendCommand("reseterror");
+ SendCommand("reseterror");
}
+ /// <summary>
+ /// Evals the specified javascript.
+ /// </summary>
+ /// <param name="javascript">The javascript.</param>
+ /// <returns></returns>
public Document Eval(string javascript){
return Eval(javascript, new Document());
}
+ /// <summary>
+ /// Evals the specified javascript.
+ /// </summary>
+ /// <param name="javascript">The javascript.</param>
+ /// <param name="scope">The scope.</param>
+ /// <returns></returns>
public Document Eval(string javascript, Document scope){
return Eval(new CodeWScope(javascript, scope));
}
- public Document Eval(CodeWScope cw){
- Document cmd = new Document().Append("$eval", cw);
+ /// <summary>
+ /// Evals the specified code scope.
+ /// </summary>
+ /// <param name="codeScope">The code scope.</param>
+ /// <returns></returns>
+ public Document Eval(CodeWScope codeScope){
+ var cmd = new Document().Append("$eval", codeScope);
return SendCommand(cmd);
}
+ /// <summary>
+ /// Sends the command.
+ /// </summary>
+ /// <param name="command">The command.</param>
+ /// <returns></returns>
public Document SendCommand(string command){
AuthenticateIfRequired();
return SendCommandCore(command);
}
+ /// <summary>
+ /// Sends the command.
+ /// </summary>
+ /// <param name="cmd">The CMD.</param>
+ /// <returns></returns>
public Document SendCommand(Document cmd){
AuthenticateIfRequired();
return SendCommandCore(cmd);
}
- private Document SendCommandCore(string command)
- {
- var cmd = new Document().Append(command,1.0);
+ /// <summary>
+ /// Sends the command core.
+ /// </summary>
+ /// <param name="command">The command.</param>
+ /// <returns></returns>
+ private Document SendCommandCore(string command){
+ var cmd = new Document().Append(command, 1.0);
return SendCommandCore(cmd);
}
- private Document SendCommandCore(Document cmd)
- {
- Document result = this.command.FindOne(cmd);
- double ok = (double)result["ok"];
- if(ok != 1.0)
- {
+ /// <summary>
+ /// Sends the command core.
+ /// </summary>
+ /// <param name="cmd">The CMD.</param>
+ /// <returns></returns>
+ private Document SendCommandCore(Document cmd){
+ var result = _command.FindOne(cmd);
+ var ok = (double)result["ok"];
+ if(ok != 1.0){
var msg = string.Empty;
if(result.Contains("msg"))
- {
msg = (string)result["msg"];
- }
else if(result.Contains("errmsg"))
- {
msg = (string)result["errmsg"];
- }
throw new MongoCommandException(msg, result, cmd);
}
return result;
}
/// <summary>
- /// Authenticates the on first request.
+ /// Authenticates the on first request.
/// </summary>
- private void AuthenticateIfRequired()
- {
- if(connection.IsAuthenticated)
+ private void AuthenticateIfRequired(){
+ if(_connection.IsAuthenticated)
return;
- var builder = new MongoConnectionStringBuilder(connection.ConnectionString);
-
+ var builder = new MongoConnectionStringBuilder(_connection.ConnectionString);
+
if(string.IsNullOrEmpty(builder.Username))
return;
@@ -186,35 +261,32 @@ private void AuthenticateIfRequired()
throw new MongoException("Error retrieving nonce", null);
var pwd = Hash(builder.Username + ":mongo:" + builder.Password);
- var auth = new Document
- {
+ var auth = new Document{
{"authenticate", 1.0},
{"user", builder.Username},
{"nonce", nonce},
{"key", Hash(nonce + builder.Username + pwd)}
};
- try
- {
+ try{
SendCommandCore(auth);
}
- catch(MongoCommandException exception)
- {
+ catch(MongoCommandException exception){
//Todo: use custom exception?
throw new MongoException("Authentication faild for " + builder.Username, exception);
}
- connection.MaskAuthenticated();
+ _connection.MaskAuthenticated();
}
/// <summary>
- /// Hashes the specified text.
+ /// Hashes the specified text.
/// </summary>
- /// <param name="text">The text.</param>
+ /// <param name = "text">The text.</param>
/// <returns></returns>
internal static string Hash(string text){
- MD5 md5 = MD5.Create();
- byte[] hash = md5.ComputeHash(Encoding.Default.GetBytes(text));
- return BitConverter.ToString(hash).Replace("-","").ToLower();
+ var md5 = MD5.Create();
+ var hash = md5.ComputeHash(Encoding.Default.GetBytes(text));
+ return BitConverter.ToString(hash).Replace("-", "").ToLower();
}
}
}
View
2  MongoDBDriver/DatabaseJS.cs
@@ -10,7 +10,7 @@ public class DatabaseJS : ICollection<Document>
{
//private Connection connection;
private Database db;
- private IMongoCollection js;
+ private IMongoCollection<Document> js;
internal DatabaseJS (Database db){
this.db = db;
View
10 MongoDBDriver/DatabaseMetaData.cs
@@ -47,7 +47,7 @@ public Boolean DropCollection(MongoCollection<Document> col)
}
public void AddUser(string username, string password){
- IMongoCollection users = db["system.users"];
+ IMongoCollection<Document> users = db["system.users"];
string pwd = Database.Hash(username + ":mongo:" + password);
Document user = new Document().Append("user", username).Append("pwd", pwd);
@@ -57,13 +57,13 @@ public Boolean DropCollection(MongoCollection<Document> col)
users.Insert(user);
}
- public void RemoveUser(string username){
- IMongoCollection users = db["system.users"];
+ public void RemoveUser(string username){
+ IMongoCollection<Document> users = db["system.users"];
users.Delete(new Document().Append("user", username));
}
- public ICursor<Document> ListUsers(){
- IMongoCollection users = db["system.users"];
+ public ICursor<Document> ListUsers(){
+ IMongoCollection<Document> users = db["system.users"];
return users.FindAll();
}
View
336 MongoDBDriver/IMongoCollection.cs
@@ -3,94 +3,129 @@
namespace MongoDB.Driver
{
- public interface IMongoCollection
+ public interface IMongoCollection<T> where T : class
{
/// <summary>
- /// Gets the database.
+ /// Gets the database.
/// </summary>
/// <value>The database.</value>
Database Database { get; }
/// <summary>
- /// Gets or sets the name.
+ /// Gets or sets the name.
/// </summary>
/// <value>The name.</value>
string Name { get; }
/// <summary>
- /// Gets or sets the name of the database.
+ /// Gets or sets the name of the database.
/// </summary>
/// <value>The name of the database.</value>
string DatabaseName { get; }
/// <summary>
- /// Gets the full name including database name.
+ /// Gets the full name including database name.
/// </summary>
/// <value>The full name.</value>
string FullName { get; }
/// <summary>
- /// Gets the meta data.
+ /// Gets the meta data.
/// </summary>
/// <value>The meta data.</value>
CollectionMetaData MetaData { get; }
/// <summary>
- /// Finds and returns the first document in a query.
+ /// Finds and returns the first document in a query.
/// </summary>
- /// <param name="spec">A <see cref="Document"/> representing the query.</param>
+ /// <param name = "spec">A <see cref = "Document" /> representing the query.</param>
/// <returns>
- /// A <see cref="Document"/> from the collection.
+ /// A <see cref = "Document" /> from the collection.
/// </returns>
- Document FindOne(Document spec);
+ T FindOne(Document spec);
/// <summary>
- /// Finds all.
+ /// Finds and returns the first document in a query.
/// </summary>
+ /// <param name = "spec">A <see cref = "Document" /> representing the query.</param>
+ /// <returns>
+ /// A <see cref = "Document" /> from the collection.
+ /// </returns>
+ T FindOne(object spec);
+
+ /// <summary>
+ /// Finds all.
+ /// </summary>
+ /// <returns></returns>
+ ICursor<T> FindAll();
+
+ /// <summary>
+ /// Finds the specified where.
+ /// </summary>
+ /// <param name = "where">The where.</param>
+ /// <returns></returns>
+ ICursor<T> Find(String where);
+
+ /// <summary>
+ /// Finds the specified spec.
+ /// </summary>
+ /// <param name = "spec">The spec.</param>
+ /// <returns></returns>
+ ICursor<T> Find(Document spec);
+
+ /// <summary>
+ /// Finds the specified spec.
+ /// </summary>
+ /// <param name = "spec">The spec.</param>
/// <returns></returns>
- ICursor<Document> FindAll();
+ ICursor<T> Find(object spec);
/// <summary>
- /// Finds the specified where.
+ /// Finds the specified spec.
/// </summary>
- /// <param name="where">The where.</param>
+ /// <param name = "spec">The spec.</param>
+ /// <param name = "limit">The limit.</param>
+ /// <param name = "skip">The skip.</param>
/// <returns></returns>
- ICursor<Document> Find(String where);
+ ICursor<T> Find(Document spec, int limit, int skip);
/// <summary>
- /// Finds the specified spec.
+ /// Finds the specified spec.
/// </summary>
- /// <param name="spec">The spec.</param>
+ /// <param name = "spec">The spec.</param>
+ /// <param name = "limit">The limit.</param>
+ /// <param name = "skip">The skip.</param>
/// <returns></returns>
- ICursor<Document> Find(Document spec);
+ ICursor<T> Find(object spec, int limit, int skip);
/// <summary>
- /// Finds the specified spec.
+ /// Finds the specified spec.
/// </summary>
- /// <param name="spec">The spec.</param>
- /// <param name="limit">The limit.</param>
- /// <param name="skip">The skip.</param>
+ /// <param name = "spec">The spec.</param>
+ /// <param name = "limit">The limit.</param>
+ /// <param name = "skip">The skip.</param>
+ /// <param name = "fields">The fields.</param>
/// <returns></returns>
- ICursor<Document> Find(Document spec, int limit, int skip);
+ ICursor<T> Find(Document spec, int limit, int skip, Document fields);
/// <summary>
- /// Finds the specified spec.
+ /// Finds the specified spec.
/// </summary>
- /// <param name="spec">The spec.</param>
- /// <param name="limit">The limit.</param>
- /// <param name="skip">The skip.</param>
- /// <param name="fields">The fields.</param>
+ /// <param name = "spec">The spec.</param>
+ /// <param name = "limit">The limit.</param>
+ /// <param name = "skip">The skip.</param>
+ /// <param name = "fields">The fields.</param>
/// <returns></returns>
- ICursor<Document> Find(Document spec, int limit, int skip, Document fields);
+ ICursor<T> Find(object spec, int limit, int skip, object fields);
/// <summary>
- /// Entrypoint into executing a map/reduce query against the collection.
+ /// Entrypoint into executing a map/reduce query against the collection.
/// </summary>
- /// <returns>A <see cref="MongoCollection.MapReduce"/></returns>
+ /// <returns></returns>
MapReduce MapReduce();
/// <summary>
- /// Maps the reduce builder.
+ /// Maps the reduce builder.
/// </summary>
/// <returns></returns>
MapReduceBuilder MapReduceBuilder();
@@ -101,132 +136,261 @@ public interface IMongoCollection
long Count();
/// <summary>
- /// Count all items in a collection that match the query spec.
+ /// Count all items in a collection that match the query spec.
/// </summary>
- /// <param name="spec">The spec.</param>
+ /// <param name = "spec">The spec.</param>
/// <returns></returns>
/// <remarks>
- /// It will return 0 if the collection doesn't exist yet.
+ /// It will return 0 if the collection doesn't exist yet.
/// </remarks>
long Count(Document spec);
/// <summary>
+ /// Count all items in a collection that match the query spec.
+ /// </summary>
+ /// <param name = "spec">The spec.</param>
+ /// <returns></returns>
+ /// <remarks>
+ /// It will return 0 if the collection doesn't exist yet.
+ /// </remarks>
+ long Count(object spec);
+
+ /// <summary>
/// Inserts the Document into the collection.
/// </summary>
void Insert(Document document, bool safemode);
/// <summary>
- /// Inserts the specified doc.
+ /// Inserts the Document into the collection.
+ /// </summary>
+ void Insert(object document, bool safemode);
+
+ /// <summary>
+ /// Inserts the specified doc.
/// </summary>
- /// <param name="document">The doc.</param>
+ /// <param name = "document">The doc.</param>
void Insert(Document document);
/// <summary>
- /// Inserts the specified documents.
+ /// Inserts the specified doc.
/// </summary>
- /// <param name="documents">The documents.</param>
- /// <param name="safemode">if set to <c>true</c> [safemode].</param>
+ /// <param name = "document">The doc.</param>
+ void Insert(object document);
+
+ /// <summary>
+ /// Inserts the specified documents.
+ /// </summary>
+ /// <param name = "documents">The documents.</param>
+ /// <param name = "safemode">if set to <c>true</c> [safemode].</param>
void Insert(IEnumerable<Document> documents, bool safemode);
/// <summary>
- /// Inserts the specified documents.
+ /// Inserts the specified documents.
/// </summary>
- /// <param name="documents">The documents.</param>
+ /// <param name = "documents">The documents.</param>
+ /// <param name = "safemode">if set to <c>true</c> [safemode].</param>
+ void Insert<TElement>(IEnumerable<TElement> documents, bool safemode);
+
+ /// <summary>
+ /// Inserts the specified documents.
+ /// </summary>
+ /// <param name = "documents">The documents.</param>
void Insert(IEnumerable<Document> documents);
/// <summary>
- /// Deletes documents from the collection according to the spec.
+ /// Inserts the specified documents.
/// </summary>
- /// <param name="selector">The selector.</param>
- /// <param name="safemode">if set to <c>true</c> [safemode].</param>
+ /// <param name = "documents">The documents.</param>
+ void Insert<TElement>(IEnumerable<TElement> documents);
+
+ /// <summary>
+ /// Deletes documents from the collection according to the spec.
+ /// </summary>
+ /// <param name = "selector">The selector.</param>
+ /// <param name = "safemode">if set to <c>true</c> [safemode].</param>
/// <remarks>
- /// An empty document will match all documents in the collection and effectively truncate it.
+ /// An empty document will match all documents in the collection and effectively truncate it.
/// </remarks>
void Delete(Document selector, bool safemode);
/// <summary>
- /// Deletes documents from the collection according to the spec.
+ /// Deletes documents from the collection according to the spec.
+ /// </summary>
+ /// <param name = "selector">The selector.</param>
+ /// <param name = "safemode">if set to <c>true</c> [safemode].</param>
+ /// <remarks>
+ /// An empty document will match all documents in the collection and effectively truncate it.
+ /// </remarks>
+ void Delete(object selector, bool safemode);
+
+ /// <summary>
+ /// Deletes documents from the collection according to the spec.
/// </summary>
- /// <param name="selector">The selector.</param>
+ /// <param name = "selector">The selector.</param>
/// <remarks>
- /// An empty document will match all documents in the collection and effectively truncate it.
+ /// An empty document will match all documents in the collection and effectively truncate it.
/// </remarks>
void Delete(Document selector);
/// <summary>
- /// Updates the specified document.
+ /// Deletes documents from the collection according to the spec.
+ /// </summary>
+ /// <param name = "selector">The selector.</param>
+ /// <remarks>
+ /// An empty document will match all documents in the collection and effectively truncate it.
+ /// </remarks>
+ void Delete(object selector);
+
+ /// <summary>
+ /// Updates the specified document.
/// </summary>
- /// <param name="document">The document.</param>
- /// <param name="safemode">if set to <c>true</c> [safemode].</param>
+ /// <param name = "document">The document.</param>
+ /// <param name = "safemode">if set to <c>true</c> [safemode].</param>
void Update(Document document, bool safemode);
/// <summary>
- /// Updates a document with the data in doc as found by the selector.
+ /// Updates the specified document.
+ /// </summary>
+ /// <param name = "document">The document.</param>
+ /// <param name = "safemode">if set to <c>true</c> [safemode].</param>
+ void Update(object document, bool safemode);
+
+ /// <summary>
+ /// Updates a document with the data in doc as found by the selector.
/// </summary>
- /// <param name="document">The document.</param>
+ /// <param name = "document">The document.</param>
/// <remarks>
- /// _id will be used in the document to create a selector. If it isn't in
- /// the document then it is assumed that the document is new and an upsert is sent to the database
- /// instead.
+ /// _id will be used in the document to create a selector. If it isn't in
+ /// the document then it is assumed that the document is new and an upsert is sent to the database
+ /// instead.
/// </remarks>
void Update(Document document);
/// <summary>
- /// Updates the specified document.
+ /// Updates a document with the data in doc as found by the selector.
+ /// </summary>
+ /// <param name = "document">The document.</param>
+ /// <remarks>
+ /// _id will be used in the document to create a selector. If it isn't in
+ /// the document then it is assumed that the document is new and an upsert is sent to the database
+ /// instead.
+ /// </remarks>
+ void Update(object document);
+
+ /// <summary>
+ /// Updates the specified document.
/// </summary>
- /// <param name="document">The document.</param>
- /// <param name="selector">The selector.</param>
- /// <param name="safemode">if set to <c>true</c> [safemode].</param>
+ /// <param name = "document">The document.</param>
+ /// <param name = "selector">The selector.</param>
+ /// <param name = "safemode">if set to <c>true</c> [safemode].</param>
void Update(Document document, Document selector, bool safemode);
/// <summary>
- /// Updates a document with the data in doc as found by the selector.
+ /// Updates the specified document.
/// </summary>
- /// <param name="document">The document.</param>
- /// <param name="selector">The selector.</param>
+ /// <param name = "document">The document.</param>
+ /// <param name = "selector">The selector.</param>
+ /// <param name = "safemode">if set to <c>true</c> [safemode].</param>
+ void Update(object document, object selector, bool safemode);
+
+ /// <summary>
+ /// Updates a document with the data in doc as found by the selector.
+ /// </summary>
+ /// <param name = "document">The document.</param>
+ /// <param name = "selector">The selector.</param>
void Update(Document document, Document selector);
/// <summary>
- /// Updates the specified document.
+ /// Updates a document with the data in doc as found by the selector.
/// </summary>
- /// <param name="document">The document.</param>
- /// <param name="selector">The selector.</param>
- /// <param name="flags">The flags.</param>
- /// <param name="safemode">if set to <c>true</c> [safemode].</param>
+ /// <param name = "document">The document.</param>
+ /// <param name = "selector">The selector.</param>
+ void Update(object document, object selector);
+
+ /// <summary>
+ /// Updates the specified document.
+ /// </summary>
+ /// <param name = "document">The document.</param>
+ /// <param name = "selector">The selector.</param>
+ /// <param name = "flags">The flags.</param>
+ /// <param name = "safemode">if set to <c>true</c> [safemode].</param>
void Update(Document document, Document selector, UpdateFlags flags, bool safemode);
/// <summary>
- /// Updates a document with the data in doc as found by the selector.
+ /// Updates the specified document.
+ /// </summary>
+ /// <param name = "document">The document.</param>
+ /// <param name = "selector">The selector.</param>
+ /// <param name = "flags">The flags.</param>
+ /// <param name = "safemode">if set to <c>true</c> [safemode].</param>
+ void Update(object document, object selector, UpdateFlags flags, bool safemode);
+
+ /// <summary>
+ /// Updates a document with the data in doc as found by the selector.
/// </summary>
- /// <param name="document">The <see cref="Document"/> to update with</param>
- /// <param name="selector">The query spec to find the document to update.</param>
- /// <param name="flags"><see cref="UpdateFlags"/></param>
+ /// <param name = "document">The <see cref = "Document" /> to update with</param>
+ /// <param name = "selector">The query spec to find the document to update.</param>
+ /// <param name = "flags"><see cref = "UpdateFlags" /></param>
void Update(Document document, Document selector, UpdateFlags flags);
/// <summary>
- /// Runs a multiple update query against the database. It will wrap any
- /// doc with $set if the passed in doc doesn't contain any '$' ops.
+ /// Updates a document with the data in doc as found by the selector.
/// </summary>
- /// <param name="document">The document.</param>
- /// <param name="selector">The selector.</param>
+ /// <param name = "document">The <see cref = "Document" /> to update with</param>
+ /// <param name = "selector">The query spec to find the document to update.</param>
+ /// <param name = "flags"><see cref = "UpdateFlags" /></param>
+ void Update(object document, object selector, UpdateFlags flags);
+
+ /// <summary>
+ /// Runs a multiple update query against the database. It will wrap any
+ /// doc with $set if the passed in doc doesn't contain any '$' ops.
+ /// </summary>
+ /// <param name = "document">The document.</param>
+ /// <param name = "selector">The selector.</param>
void UpdateAll(Document document, Document selector);
/// <summary>
- /// Updates all.
+ /// Runs a multiple update query against the database. It will wrap any
+ /// doc with $set if the passed in doc doesn't contain any '$' ops.
/// </summary>
- /// <param name="document">The document.</param>
- /// <param name="selector">The selector.</param>
- /// <param name="safemode">if set to <c>true</c> [safemode].</param>
+ /// <param name = "document">The document.</param>
+ /// <param name = "selector">The selector.</param>
+ void UpdateAll(object document, object selector);
+
+ /// <summary>
+ /// Updates all.
+ /// </summary>
+ /// <param name = "document">The document.</param>
+ /// <param name = "selector">The selector.</param>
+ /// <param name = "safemode">if set to <c>true</c> [safemode].</param>
void UpdateAll(Document document, Document selector, bool safemode);
/// <summary>
- /// Saves a document to the database using an upsert.
+ /// Updates all.
/// </summary>
- /// <param name="document">The document.</param>
+ /// <param name = "document">The document.</param>
+ /// <param name = "selector">The selector.</param>
+ /// <param name = "safemode">if set to <c>true</c> [safemode].</param>
+ void UpdateAll(object document, object selector, bool safemode);
+
+ /// <summary>
+ /// Saves a document to the database using an upsert.
+ /// </summary>
+ /// <param name = "document">The document.</param>
/// <remarks>
- /// The document will contain the _id that is saved to the database. This is really just an alias
- /// to Update(Document) to maintain consistency between drivers.
+ /// The document will contain the _id that is saved to the database. This is really just an alias
+ /// to Update(Document) to maintain consistency between drivers.
/// </remarks>
void Save(Document document);
+
+ /// <summary>
+ /// Saves a document to the database using an upsert.
+ /// </summary>
+ /// <param name = "document">The document.</param>
+ /// <remarks>
+ /// The document will contain the _id that is saved to the database. This is really just an alias
+ /// to Update(Document) to maintain consistency between drivers.
+ /// </remarks>
+ void Save(object document);
}
-}
+}
View
7 MongoDBDriver/IMongoCollection´1.cs
@@ -1,7 +0,0 @@
-namespace MongoDB.Driver
-{
- public interface IMongoCollection<T> : IMongoCollection
- {
-
- }
-}
View
356 MongoDBDriver/MongoCollection.cs
@@ -10,6 +10,7 @@ namespace MongoDB.Driver
///
/// </summary>
public class MongoCollection<T> : IMongoCollection<T>
+ where T : class
{
private static readonly OidGenerator OidGenerator = new OidGenerator();
private readonly Connection _connection;
@@ -72,10 +73,24 @@ public class MongoCollection<T> : IMongoCollection<T>
/// <returns>
/// A <see cref="Document"/> from the collection.
/// </returns>
- public Document FindOne(Document spec){
- var cur = Find(spec, -1, 0, null);
- foreach(var doc in cur.Documents){
- cur.Dispose();
+ public T FindOne(Document spec)
+ {
+ return FindOne((object)spec);
+ }
+
+ /// <summary>
+ /// Finds and returns the first document in a query.
+ /// </summary>
+ /// <param name="spec">A <see cref="Document"/> representing the query.</param>
+ /// <returns>
+ /// A <see cref="Document"/> from the collection.
+ /// </returns>
+ public T FindOne(object spec)
+ {
+ var cursor = Find(spec, -1, 0, null);
+ foreach(var doc in cursor.Documents)
+ {
+ cursor.Dispose();
return doc;
}
//FIXME Decide if this should throw a not found exception instead of returning null.
@@ -86,7 +101,7 @@ public class MongoCollection<T> : IMongoCollection<T>
/// Finds all.
/// </summary>
/// <returns></returns>
- public ICursor<Document> FindAll()
+ public ICursor<T> FindAll()
{
var spec = new Document();
return Find(spec, 0, 0, null);
@@ -97,7 +112,7 @@ public ICursor<Document> FindAll()
/// </summary>
/// <param name="where">The where.</param>
/// <returns></returns>
- public ICursor<Document> Find(String where)
+ public ICursor<T> Find(String where)
{
var spec = new Document();
spec.Append("$where", new Code(where));
@@ -109,7 +124,17 @@ public ICursor<Document> Find(String where)
/// </summary>
/// <param name="spec">The spec.</param>
/// <returns></returns>
- public ICursor<Document> Find(Document spec)
+ public ICursor<T> Find(Document spec)
+ {
+ return Find((object)spec);
+ }
+
+ /// <summary>
+ /// Finds the specified spec.
+ /// </summary>
+ /// <param name="spec">The spec.</param>
+ /// <returns></returns>
+ public ICursor<T> Find(object spec)
{
return Find(spec, 0, 0, null);
}
@@ -121,7 +146,19 @@ public ICursor<Document> Find(Document spec)
/// <param name="limit">The limit.</param>
/// <param name="skip">The skip.</param>
/// <returns></returns>
- public ICursor<Document> Find(Document spec, int limit, int skip)
+ public ICursor<T> Find(Document spec, int limit, int skip)
+ {
+ return Find((object)spec, limit, skip, null);
+ }
+
+ /// <summary>
+ /// Finds the specified spec.
+ /// </summary>
+ /// <param name="spec">The spec.</param>
+ /// <param name="limit">The limit.</param>
+ /// <param name="skip">The skip.</param>
+ /// <returns></returns>
+ public ICursor<T> Find(object spec, int limit, int skip)
{
return Find(spec, limit, skip, null);
}
@@ -134,11 +171,24 @@ public ICursor<Document> Find(Document spec, int limit, int skip)
/// <param name="skip">The skip.</param>
/// <param name="fields">The fields.</param>
/// <returns></returns>
- public ICursor<Document> Find(Document spec, int limit, int skip, Document fields)
+ public ICursor<T> Find(Document spec, int limit, int skip, Document fields)
+ {
+ return Find((object)spec, limit, skip, (object)fields);
+ }
+
+ /// <summary>
+ /// Finds the specified spec.
+ /// </summary>
+ /// <param name="spec">The spec.</param>
+ /// <param name="limit">The limit.</param>
+ /// <param name="skip">The skip.</param>
+ /// <param name="fields">The fields.</param>
+ /// <returns></returns>
+ public ICursor<T> Find(object spec, int limit, int skip, object fields)
{
if(spec == null)
spec = new Document();
- return new Cursor<Document>(_connection, FullName, spec, limit, skip, fields);
+ return new Cursor<T>(_connection, FullName, spec, limit, skip, fields);
}
/// <summary>
@@ -173,11 +223,26 @@ public ICursor<Document> Find(Document spec, int limit, int skip, Document field
/// It will return 0 if the collection doesn't exist yet.
/// </remarks>
public long Count(Document spec){
- try{
+ return Count((object)spec);
+ }
+
+ /// <summary>
+ /// Count all items in a collection that match the query spec.
+ /// </summary>
+ /// <param name="spec">The spec.</param>
+ /// <returns></returns>
+ /// <remarks>
+ /// It will return 0 if the collection doesn't exist yet.
+ /// </remarks>
+ public long Count(object spec)
+ {
+ try
+ {
var response = Database.SendCommand(new Document().Append("count", Name).Append("query", spec));
return Convert.ToInt64((double)response["n"]);
}
- catch(MongoCommandException){
+ catch(MongoCommandException)
+ {
//FIXME This is an exception condition when the namespace is missing.
//-1 might be better here but the console returns 0.
return 0;
@@ -188,6 +253,14 @@ public ICursor<Document> Find(Document spec, int limit, int skip, Document field
/// Inserts the Document into the collection.
/// </summary>
public void Insert(Document document, bool safemode){
+ Insert((object)document,safemode);
+ }
+
+ /// <summary>
+ /// Inserts the Document into the collection.
+ /// </summary>
+ public void Insert(object document, bool safemode)
+ {
Insert(document);
CheckError(safemode);
}
@@ -197,8 +270,16 @@ public ICursor<Document> Find(Document spec, int limit, int skip, Document field
/// </summary>
/// <param name="document">The doc.</param>
public void Insert(Document document){
- var docs = new[]{document};
- Insert(docs);
+ Insert((object)document);
+ }
+
+ /// <summary>
+ /// Inserts the specified doc.
+ /// </summary>
+ /// <param name="document">The doc.</param>
+ public void Insert(object document)
+ {
+ Insert(new[] { document });
}
/// <summary>
@@ -206,7 +287,18 @@ public ICursor<Document> Find(Document spec, int limit, int skip, Document field
/// </summary>
/// <param name="documents">The documents.</param>
/// <param name="safemode">if set to <c>true</c> [safemode].</param>
- public void Insert(IEnumerable<Document> documents, bool safemode){
+ public void Insert(IEnumerable<Document> documents, bool safemode)
+ {
+ Insert((IEnumerable<object>)documents, safemode);
+ }
+
+ /// <summary>
+ /// Inserts the specified documents.
+ /// </summary>
+ /// <param name="documents">The documents.</param>
+ /// <param name="safemode">if set to <c>true</c> [safemode].</param>
+ public void Insert<TElement>(IEnumerable<TElement> documents, bool safemode)
+ {
if(safemode)
Database.ResetError();
Insert(documents);
@@ -218,24 +310,41 @@ public ICursor<Document> Find(Document spec, int limit, int skip, Document field
/// </summary>
/// <param name="documents">The documents.</param>
public void Insert(IEnumerable<Document> documents){
- var insertMessage = new InsertMessage<Document>{
+ Insert((IEnumerable<object>)documents);
+ }
+
+ /// <summary>
+ /// Inserts the specified documents.
+ /// </summary>
+ /// <param name="documents">The documents.</param>
+ public void Insert<TElement>(IEnumerable<TElement> documents)
+ {
+ var insertMessage = new InsertMessage
+ {
FullCollectionName = FullName
};
- var insertDocument = new List<Document>();
+ var insertDocument = new List<object>();
+ //Fixme: This should be handled by an external class
+ /*
foreach(var doc in documents)
- if(doc.Contains("_id") == false){
+ if(doc.Contains("_id") == false)
+ {
doc.Prepend("_id", OidGenerator.Generate());
}
-
- insertDocument.AddRange(documents);
+ */
+ foreach(var document in documents)
+ insertDocument.Add(document);
+
insertMessage.Documents = insertDocument.ToArray();
-
- try{
+
+ try
+ {
_connection.SendMessage(insertMessage);
}
- catch(IOException exception){
+ catch(IOException exception)
+ {
throw new MongoCommException("Could not insert document, communication failure", _connection, exception);
}
}
@@ -249,6 +358,19 @@ public ICursor<Document> Find(Document spec, int limit, int skip, Document field
/// An empty document will match all documents in the collection and effectively truncate it.
/// </remarks>
public void Delete(Document selector, bool safemode){
+ Delete((object)selector, safemode);
+ }
+
+ /// <summary>
+ /// Deletes documents from the collection according to the spec.
+ /// </summary>
+ /// <param name="selector">The selector.</param>
+ /// <param name="safemode">if set to <c>true</c> [safemode].</param>
+ /// <remarks>
+ /// An empty document will match all documents in the collection and effectively truncate it.
+ /// </remarks>
+ public void Delete(object selector, bool safemode)
+ {
Delete(selector);
CheckError(safemode);
}
@@ -261,15 +383,30 @@ public ICursor<Document> Find(Document spec, int limit, int skip, Document field
/// An empty document will match all documents in the collection and effectively truncate it.
/// </remarks>
public void Delete(Document selector){
- var deleteMessage = new DeleteMessage{
- FullCollectionName = FullName,
+ Delete((object)selector);
+ }
+
+ /// <summary>
+ /// Deletes documents from the collection according to the spec.
+ /// </summary>
+ /// <param name="selector">The selector.</param>
+ /// <remarks>
+ /// An empty document will match all documents in the collection and effectively truncate it.
+ /// </remarks>
+ public void Delete(object selector)
+ {
+ var deleteMessage = new DeleteMessage
+ {
+ FullCollectionName = FullName,
Selector = selector
};
- try{
+ try
+ {
_connection.SendMessage(deleteMessage);
}
- catch(IOException exception){
+ catch(IOException exception)
+ {
throw new MongoCommException("Could not delete document, communication failure", _connection, exception);
}
}
@@ -280,6 +417,16 @@ public ICursor<Document> Find(Document spec, int limit, int skip, Document field
/// <param name="document">The document.</param>
/// <param name="safemode">if set to <c>true</c> [safemode].</param>
public void Update(Document document, bool safemode){
+ Update((object)document,safemode);
+ }
+
+ /// <summary>
+ /// Updates the specified document.
+ /// </summary>
+ /// <param name="document">The document.</param>
+ /// <param name="safemode">if set to <c>true</c> [safemode].</param>
+ public void Update(object document, bool safemode)
+ {
Update(document);
CheckError(safemode);
}
@@ -293,19 +440,39 @@ public ICursor<Document> Find(Document spec, int limit, int skip, Document field
/// the document then it is assumed that the document is new and an upsert is sent to the database
/// instead.
/// </remarks>
- public void Update(Document document){
+ public void Update(Document document)
+ {
+ Update((object)document);
+ }
+
+ /// <summary>
+ /// Updates a document with the data in doc as found by the selector.
+ /// </summary>
+ /// <param name="document">The document.</param>
+ /// <remarks>
+ /// _id will be used in the document to create a selector. If it isn't in
+ /// the document then it is assumed that the document is new and an upsert is sent to the database
+ /// instead.
+ /// </remarks>
+ public void Update(object document)
+ {
//Try to generate a selector using _id for an existing document.
//otherwise just set the upsert flag to 1 to insert and send onward.
var selector = new Document();
var upsert = UpdateFlags.Upsert;
-
- if(document.Contains("_id") & document["_id"] != null)
+
+ //Todo: this needs to be cheched in an external class
+ /*
+ if(document.Contains("_id") & document["_id"] != null)
selector["_id"] = document["_id"];
- else{
+ else
+ {
//Likely a new document
document.Prepend("_id", OidGenerator.Generate());
upsert = UpdateFlags.Upsert;
}
+ * */
+
Update(document, selector, upsert);
}
@@ -315,7 +482,19 @@ public ICursor<Document> Find(Document spec, int limit, int skip, Document field
/// <param name="document">The document.</param>
/// <param name="selector">The selector.</param>
/// <param name="safemode">if set to <c>true</c> [safemode].</param>
- public void Update(Document document, Document selector, bool safemode){
+ public void Update(Document document, Document selector, bool safemode)
+ {
+ Update((object)document, (object)document, safemode);
+ }
+
+ /// <summary>
+ /// Updates the specified document.
+ /// </summary>
+ /// <param name="document">The document.</param>
+ /// <param name="selector">The selector.</param>
+ /// <param name="safemode">if set to <c>true</c> [safemode].</param>
+ public void Update(object document, object selector, bool safemode)
+ {
Update(document, selector, 0, safemode);
}
@@ -324,7 +503,17 @@ public ICursor<Document> Find(Document spec, int limit, int skip, Document field
/// </summary>
/// <param name="document">The document.</param>
/// <param name="selector">The selector.</param>
- public void Update(Document document, Document selector){
+ public void Update(Document document, Document selector)
+ {
+ Update((object)document, (object)selector);
+ }
+ /// <summary>
+ /// Updates a document with the data in doc as found by the selector.
+ /// </summary>
+ /// <param name="document">The document.</param>
+ /// <param name="selector">The selector.</param>
+ public void Update(object document, object selector)
+ {
Update(document, selector, 0);
}
@@ -335,7 +524,20 @@ public ICursor<Document> Find(Document spec, int limit, int skip, Document field
/// <param name="selector">The selector.</param>
/// <param name="flags">The flags.</param>
/// <param name="safemode">if set to <c>true</c> [safemode].</param>
- public void Update(Document document, Document selector, UpdateFlags flags, bool safemode){
+ public void Update(Document document, Document selector, UpdateFlags flags, bool safemode)
+ {
+ Update((object)document, (object)selector, flags, safemode);
+ }
+
+ /// <summary>
+ /// Updates the specified document.
+ /// </summary>
+ /// <param name="document">The document.</param>
+ /// <param name="selector">The selector.</param>
+ /// <param name="flags">The flags.</param>
+ /// <param name="safemode">if set to <c>true</c> [safemode].</param>
+ public void Update(object document, object selector, UpdateFlags flags, bool safemode)
+ {
Update(document, selector, flags);
CheckError(safemode);
}
@@ -346,18 +548,32 @@ public ICursor<Document> Find(Document spec, int limit, int skip, Document field
/// <param name="document">The <see cref="Document"/> to update with</param>
/// <param name="selector">The query spec to find the document to update.</param>
/// <param name="flags"><see cref="UpdateFlags"/></param>
- public void Update(Document document, Document selector, UpdateFlags flags){
- var updateMessage = new UpdateMessage{
- FullCollectionName = FullName,
- Selector = selector,
- Document = document,
+ public void Update(Document document, Document selector, UpdateFlags flags)
+ {
+ Update((object)document, (object)selector, flags);
+ }
+ /// <summary>
+ /// Updates a document with the data in doc as found by the selector.
+ /// </summary>
+ /// <param name="document">The <see cref="Document"/> to update with</param>
+ /// <param name="selector">The query spec to find the document to update.</param>
+ /// <param name="flags"><see cref="UpdateFlags"/></param>
+ public void Update(object document, object selector, UpdateFlags flags)
+ {
+ var updateMessage = new UpdateMessage
+ {
+ FullCollectionName = FullName,
+ Selector = selector,
+ Document = document,
Flags = (int)flags
};
- try{
+ try
+ {
_connection.SendMessage(updateMessage);
}
- catch(IOException exception){
+ catch(IOException exception)
+ {
throw new MongoCommException("Could not update document, communication failure", _connection, exception);
}
}
@@ -368,20 +584,36 @@ public ICursor<Document> Find(Document spec, int limit, int skip, Document field
/// </summary>
/// <param name="document">The document.</param>
/// <param name="selector">The selector.</param>
- public void UpdateAll(Document document, Document selector){
+ public void UpdateAll(Document document, Document selector)
+ {
+ UpdateAll((object)document, (object)selector);
+ }
+
+ /// <summary>
+ /// Runs a multiple update query against the database. It will wrap any
+ /// doc with $set if the passed in doc doesn't contain any '$' ops.
+ /// </summary>
+ /// <param name="document">The document.</param>
+ /// <param name="selector">The selector.</param>
+ public void UpdateAll(object document, object selector)
+ {
var foundOp = false;
- foreach(string key in document.Keys)
- if(key.IndexOf('$') == 0){
+ //Todo: need to get this info external
+ /*
+ * foreach(string key in document.Keys)
+ if(key.IndexOf('$') == 0)
+ {
foundOp = true;
break;
- }
-
- if(foundOp == false){
+ }*/
+
+ if(foundOp == false)
+ {
//wrap document in a $set.
document = new Document().Append("$set", document);
}
-
+
Update(document, selector, UpdateFlags.MultiUpdate);
}
@@ -391,7 +623,18 @@ public ICursor<Document> Find(Document spec, int limit, int skip, Document field
/// <param name="document">The document.</param>
/// <param name="selector">The selector.</param>
/// <param name="safemode">if set to <c>true</c> [safemode].</param>
- public void UpdateAll(Document document, Document selector, bool safemode){
+ public void UpdateAll(Document document, Document selector, bool safemode)
+ {
+ UpdateAll((object)document, (object)selector);
+ }
+ /// <summary>
+ /// Updates all.
+ /// </summary>
+ /// <param name="document">The document.</param>
+ /// <param name="selector">The selector.</param>
+ /// <param name="safemode">if set to <c>true</c> [safemode].</param>
+ public void UpdateAll(object document, object selector, bool safemode)
+ {
if(safemode)
Database.ResetError();
UpdateAll(document, selector);
@@ -406,7 +649,20 @@ public ICursor<Document> Find(Document spec, int limit, int skip, Document field
/// The document will contain the _id that is saved to the database. This is really just an alias
/// to Update(Document) to maintain consistency between drivers.
/// </remarks>
- public void Save(Document document){
+ public void Save(Document document)
+ {
+ Save((object)document);
+ }
+ /// <summary>
+ /// Saves a document to the database using an upsert.
+ /// </summary>
+ /// <param name="document">The document.</param>
+ /// <remarks>
+ /// The document will contain the _id that is saved to the database. This is really just an alias
+ /// to Update(Document) to maintain consistency between drivers.
+ /// </remarks>
+ public void Save(object document)
+ {
Update(document);
}
View
1  MongoDBDriver/MongoDB.Driver.csproj
@@ -77,7 +77,6 @@
<Compile Include="Bson\DocumentDescriptor.cs" />
<Compile Include="Bson\IBsonObjectBuilder.cs" />
<Compile Include="Bson\IBsonObjectDescriptor.cs" />
- <Compile Include="IMongoCollection´1.cs" />
<Compile Include="MongoCollection.cs" />
<Compile Include="CollectionMetaData.cs" />
<Compile Include="Connections\Connection.cs" />
View
4 examples/Simple/Main.cs
@@ -16,8 +16,8 @@ namespace Simple
class MainClass
{
Mongo mongo;
- Database simple;
- IMongoCollection categories;
+ Database simple;
+ IMongoCollection<Document> categories;