With MongoDB id stored in Java LUUID (legacy representation), when a script is run to retrieve these ids, the output shows them in binary format:
var myStringArray = ["string1",
"string2"];
for (var i = 0; i < myStringArray.length; i++) {
let outputs = db.getCollection("MyCollection").aggregate(
{
'$match': {
"field1": myStringArray[i]
}
}
, { $project: { _id: 1, "field1": 1 } }
).map(function (el) { return EJSON.stringify(el) });
console.log(outputs);
}
Output:
[
'{"_id":{"$binary":{"base64":"Z0raDiKJKdjkWnqi5TvWjQ==","subType":"03"}},"field1":"string1"}'
]
[
'{"_id":{"$binary":{"base64":"a0xH8uquuKwwbsRc4LggvA==","subType":"03"}},"field1":"string2"}'
]
Would prefer to see the "_id"
shown similar to "_id": JUUID("ACB8AEEA-D247-4C6B-BC20-B8E05C146F30")
.
NOTE: I am not asking how to store in subtype 4 (standard) UUID format. The MongoDB driver is set to UuidRepresentation.JAVA_LEGACY and this will not change.
3
Answers
I came up with the following solution which works for my purposes. It borrows from this old version of some helper functions I came across. Big shout out to @aneroid for assistance with the methods.
Output:
The closest to getting a hex-representation is to use
.toString('hex', 3)
.For your data and code, use this:
Output is:
With the latest MongoDB v8.0 release, you have a new option of
$toUUID
sample data:
example syntax of
$toUUID
:sample output:
Prior to MongoDB v8.0, you may use
$function
to perform UUID conversion with javascript’shex
function. After the conversion, you can use$concat
and$substrCP
to reform your UUID string.Please be reminded:
$function
may decrease performance. From official doc,$function
is deprecated in future versions of MongoDB. From official doc,Mongo Playground