shellmongodbguid

How do I use a guid in a mongodb shell query


When using the MongoDB shell, how do I use a guid datatype (which I have used as the _id in my collection).

The following format doesn't work:

>db.person.find({"_id","E3E45566-AFE4-A564-7876-AEFF6745FF"});

Thanks.


Solution

  • You have to compare the _id value against an instance of BinData (not against a string). Unfortunately the BinData constructor takes a Base64 string instead of a hex string.

    Your GUID value is missing two hex digits at the end, so for the purposes of this example I will assume they are "00". The following values are equivalent:

    hex: "E3E45566-AFE4-A564-7876-AEFF6745FF00" (ignoring dashes)

    base64: "ZlXk4+SvZKV4dq7/Z0X/AA=="

    So your query should be:

    >db.person.find({_id : new BinData(3, "ZlXk4+SvZKV4dq7/Z0X/AA==")})

    I am assuming that the binary subtype was correctly set to 3. If not, what driver was used to create the data?