MongoDB Shell中NumberInt()在客户端JavaScript(mongodb模块)的等效实现
NumberInt(1) in the Shell) Great question! If you're using the official mongodb Node.js driver and want to replicate the behavior of NumberInt(1) from the MongoDB Shell—i.e., inserting a strict 32-bit integer instead of the default 64-bit float—here are the two most reliable ways to do it:
1. Use the Int32 Class from the Driver
The driver provides a dedicated Int32 type that maps directly to MongoDB's NumberInt BSON type. Just import/require it and create a new instance with your integer value.
Here's a complete example:
const { MongoClient, Int32 } = require('mongodb'); async function insert32BitInt() { // Connect to your MongoDB instance const client = new MongoClient('mongodb://localhost:27017'); await client.connect(); try { const db = client.db('myDatabase'); const collection = db.collection('myCollection'); // Insert a document with a 32-bit integer field const result = await collection.insertOne({ item: 'apple', quantity: new Int32(1) // This matches NumberInt(1) from the shell }); console.log(`Inserted document with ID: ${result.insertedId}`); } finally { // Always close the connection await client.close(); } } // Run the function and catch any errors insert32BitInt().catch(console.error);
2. Alternative: Use BSON's Int32 Directly
If you're working with the BSON module separately (it's a dependency of the mongodb driver), you can also use Int32 from bson:
const { Int32 } = require('bson'); // Then use it the same way: new Int32(1)
A Quick Note on Automatic Coercion
Keep in mind that if you insert a plain JavaScript number like 1 without wrapping it in Int32, MongoDB might store it as a 64-bit float (NumberDouble). While this works for many use cases, using Int32 ensures the value is stored exactly as a 32-bit integer, just like NumberInt(1) in the shell.
内容的提问来源于stack exchange,提问作者Dan Dascalescu

