import { MongoClient, Decimal128, Db, Collection } from "mongodb";
function createDecimal128FromHexBytes(hexBytes: string) {
const buffer = Buffer.from(hexBytes, "hex");
return new Decimal128(buffer);
}
const BAD_DECIMAL128_BYTES = "00000080bf48a113150dea9f9f74006c";
function createBadDecimal128() {
return createDecimal128FromHexBytes(BAD_DECIMAL128_BYTES);
}
function insertTestDocument(collection: Collection, d128: Decimal128) {
return collection.insertOne({
name: "test",
value: d128,
});
}
async function displayDocument(collection: Collection, d128: Decimal128) {
const result = await collection.aggregate([
{ $match: { value: d128 } },
{ $project: {
_id: 0,
value: 1, toDouble: { $toDouble: "$value" }, toString: { $toString: "$value" }, cmp0: { $cmp: ["$value", 0] }, }}
]).toArray();
console.log("\nAggregation result:");
console.log(JSON.stringify(result, null, 2));
}
async function testDocument(collection: Collection, d128: Decimal128) {
await insertTestDocument(collection, d128);
await displayDocument(collection, d128);
}
async function demo(collection: Collection) {
await testDocument(collection, createBadDecimal128());
}
async function main() {
const client = new MongoClient("mongodb:); // Replica set mode
await client.connect();
const db = client.db("decimal128_bug_reproduction");
const testCollection = db.collection("test");
try {
await testCollection.deleteMany({});
await demo(testCollection);
} finally {
await client.close();
}
}
main().catch(console.error);