How can I find a document by GUID _id?
See the question and my original answer on StackOverflowThe MongoDb C# driver does a lot of work trying to keep you away of the Json (Bson) representation. To oversimplify, you have 3 ways of working with MongoDb with C#
- use raw Json (which is very "server-side" progamming).
- use the Swiss army knife
BsonDocument
class. - use typed C# classes.
And of course, a combination of the 3, which makes things much worse :-)
So, in your case, here is how you would do the BsonDocument way (w/o any JSON):
var client = new MongoClient(myConnectionString);
var db = client.GetDatabase("myDb");
var guid = Guid.NewGuid();
// create an untyped document
var doc = new BsonDocument { { "_id", guid } };
var coll = db.GetCollection<BsonDocument>("myColl");
coll.InsertOne(doc);
// Builders<T> is central to help you build all sorts of mongodb JSON jargon (filters, sort, projections, etc.)
// instead of building it by yourself
var filter = Builders<BsonDocument>.Filter.Eq(new StringFieldDefinition<BsonDocument, Guid>("_id"), guid);
var foundDoc = coll.Find(filter).FirstOrDefault();
Console.WriteLine(foundDoc["_id"]);
And here is how you could do the typed-document way (w/o any JSON and w/o any BsonDocument):
var client = new MongoClient(myConnectionString);
var db = client.GetDatabase("myDb");
var guid = Guid.NewGuid();
// create a class
var doc = new MyDoc { Id = guid };
var coll = db.GetCollection<MyDoc>("myColl");
coll.InsertOne(doc);
// we use a type that correspond to our busines layer/logic
// that's the easier way because you can use Linq syntax so we're far from JSON and document issues
// plus it's super readable in C#
var foundDoc = coll.Find(d => d.Id == guid).FirstOrDefault();
Console.WriteLine(foundDoc.Id);
...
// the typed-document (class)
class MyDoc
{
[BsonId]
public Guid Id { get; set; }
... other properties...
}
As you see, the last way is much simpler, but we can't always use it. BTW, it's sad that the driver doesn't allow to derive MyDoc
from BsonDocument
, because we would truly have best of both worlds (it compiles but throws.... if MongoDb C# devs read this...)
Now, concerning guids, you'll note the Console.WriteLine(foundDoc["_id"])
displays UuidLegacy:0x87fa981983de774b998868046e257b19
because MongoDb has a legacy history with guids.
As you found out, you can change BsonDefaults.GuidRepresentation
. By default it's CSharpLegacy
.
Here is a list of prefixes used when guids are displayed as strings throughout code (client or server):
- UUID: the standard one (not legacy)
- LUUID: the legacy one (only seen on server)
- CSUUID: the C# legacy one (only seen on clients)
- JUUID: the Java legacy one (only seen on clients)
- PYUUID : the Python legacy one (only seen on clients)
The 2 and 3 approaches also shield you from these "internal" MongoDb issues. If you use these, you don't have to change BsonDefaults.GuidRepresentation
.
So my advise is try to stay away from Json when programming MongoDb with C#.