Working with GUIDs in MongoDB and ASP.NET MVC3
Just a small tip for those looking to use GUIDs as document IDs in MongoDB in conjunction with ASP.NET MVC3: it’s a lot more straightforward than it may seem at the onset.
These examples are based off of the ASP.NET MVC3 tutorials…except with MongoDB instead of EF+SQL Server.
I’ve set up my model class like so:
1 2 3 4 5 6 7 8 9 |
public class Movie { [BsonId] public Guid ID { get; set; } public string Title { get; set; } public DateTime ReleaseDate { get; set; } public string Genre { get; set; } public decimal Price { get; set; } } |
When the application creates an object and persists it to the database, you’ll see that it shows up like this in the Mongo console (I’ve formatted the JSON for clarity):
1 2 3 4 5 6 7 8 |
> db.movies.find() { "_id":BinData(3,"n2FLBkAkhEOCkX42BGXRqg=="), "Title":"Test", "ReleaseDate": ISODate("2011-05-11T04:00:00 Z"), "Genre":"Comedy", "Price":"9.99" } |
If you try to serialize this to JSON, instead of getting a GUID string, you’ll get:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
// Get a document BsonDocument document = movies.FindOneAs<BsonDocument>(); // Direct to JSON document.ToJson(); /* { "_id":new BinData(3, "n2FLBkAkhEOCkX42BGXRqg==" ), "Title":"Test", "ReleaseDate": ISODate("2011-05-11T04:00:00 Z"), "Genre":"Comedy", "Price":"9.99" } */ // With settings JsonWriterSettings settings = new JsonWriterSettings{OutputMode = JsonOutputMode.JavaScript }; document.ToJson(settings); /* { "_id":{ "$binary":"n2FLBkAkhEOCkX42BGXRqg==", "$type":"03" }, "Title":"Test", "ReleaseDate":Date(1305086400000), "Genre":"Comedy", "Price":"9.99" } */ |
This is somewhat inconvenient if you want to work with it from a pure JavaScript perspective; I was hoping that it would have returned a GUID as a string instead. I was also concerned that this meant that I’d have to manage this manually as well on the server side in my actions, but it turns out that it works better than expected. The only caveat is that you have to use “_id” when creating queries; otherwise, you can use the GUID as-is and the Mongo APIs will convert it behind the scenes:
1 2 3 4 5 6 7 8 9 |
public ActionResult Details(Guid id) { MongoCollection<Movie> movies = _database.GetCollection<Movie>("movies"); // No need to mess with the GUID; use it as is. Movie movie = movies.FindOneAs<Movie>(Query.EQ("_id", id)); return View(movie); } |
You can see the result below in the browser:
So far, so good with my little Mongo+MVC3 experiment 😀