Created
June 22, 2013 20:44
-
-
Save tekmaven/5842521 to your computer and use it in GitHub Desktop.
This is a mirror of http://www.pastie.org/1977343. It appears this site is down, and I retrieved this from the Google Cache. It contains a source code sample from a Stack Overflow answer (http://stackoverflow.com/questions/12081251/mongodb-as-a-queue-capped-collection-tailable-cursor). This is the only source code example I could find online wit…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading; | |
using MongoDB.Bson; | |
using MongoDB.Driver; | |
using MongoDB.Driver.Builders; | |
namespace TestTailableCursor { | |
public static class Program { | |
public static void Main(string[] args) { | |
try { | |
var server = MongoServer.Create("mongodb://localhost/?safe=true"); | |
var database = server["test"]; | |
if (database.CollectionExists("capped")) { | |
database.DropCollection("capped"); | |
} | |
var collectionOptions = CollectionOptions.SetCapped(true).SetMaxDocuments(5); | |
var commandResult = database.CreateCollection("capped", collectionOptions); | |
var collection = database["capped"]; | |
// to test the tailable cursor manually insert documents into the test.capped collection | |
// while this program is running and verify that they are echoed to the console window | |
// see: http://www.mongodb.org/display/DOCS/Tailable+Cursors for C++ version of this loop | |
BsonValue lastId = BsonMinKey.Value; | |
while (true) { | |
var query = Query.GT("_id", lastId); | |
var cursor = collection.Find(query) | |
.SetFlags(QueryFlags.TailableCursor | QueryFlags.AwaitData) | |
.SetSortOrder("$natural"); | |
using (var enumerator = (MongoCursorEnumerator<BsonDocument>) cursor.GetEnumerator()) { | |
while (true) { | |
if (enumerator.MoveNext()) { | |
var document = enumerator.Current; | |
lastId = document["_id"]; | |
ProcessDocument(document); | |
} else { | |
if (enumerator.IsDead) { | |
break; | |
} | |
if (!enumerator.IsServerAwaitCapable) { | |
Thread.Sleep(TimeSpan.FromMilliseconds(100)); | |
} | |
} | |
} | |
} | |
} | |
} catch (Exception ex) { | |
Console.WriteLine("Unhandled exception:"); | |
Console.WriteLine(ex); | |
} | |
Console.WriteLine("Press Enter to continue"); | |
Console.ReadLine(); | |
} | |
private static void ProcessDocument( | |
BsonDocument document | |
) { | |
Console.WriteLine(document.ToJson()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment