MongoDB 自动增长学习笔记

什么是自动增长?

在 MongoDB 中,自动增长指的是在向集合中插入文档时,由MongoDB自动为文档生成一个唯一的ID,这个ID可以作为该文档在集合中的主键。

如何启用自动增长?

要启用自动增长,需要在创建集合时指定一个字段作为主键,并将该字段的属性设置为 ObjectId 类型,例如:

Copy Code
db.createCollection("users", { validator: { $jsonSchema: { bsonType: "object", properties: { _id: { bsonType: "objectId" }, username: { bsonType: "string" }, password: { bsonType: "string" } }, required: [ "_id", "username", "password" ] } } })

上面的代码创建了一个名为 users 的新集合,并将 _id 字段设置为主键,并将其属性设置为 objectId 类型。

这样,在向 users 集合中插入文档时,如果不提供 _id 字段,MongoDB会自动为该文档生成一个唯一的 _id 值。

例如,下面的代码向 users 集合中插入了一个新用户:

Copy Code
db.users.insertOne({username: "johndoe", password: "password123"})

在执行完上述代码后,会发现数据库中已经有了一个名为 johndoe 的用户,并且该用户具有唯一的 _id 值,这个值是由MongoDB自动生成的。

自动增长的实例

下面是一个更完整的示例,展示了如何在 Node.js 中使用 MongoDB 自动增长功能:

javascriptCopy Code
const MongoClient = require('mongodb').MongoClient; const assert = require('assert'); // Connection URL const url = 'mongodb://localhost:27017'; // Database Name const dbName = 'myproject'; // Create a new MongoClient const client = new MongoClient(url); // Use connect method to connect to the Server client.connect(function(err) { assert.equal(null, err); console.log("Connected successfully to server"); const db = client.db(dbName); // Get the users collection const usersCollection = db.collection('users'); // Insert a new user into the collection usersCollection.insertOne({username: "johndoe", password: "password123"}, function(err, result) { assert.equal(err, null); console.log("User inserted"); console.log(result.ops[0]); }); // Close the client client.close(); });

上述代码中,我们首先创建了一个名为 myproject 的数据库,并在其中创建了一个名为 users 的集合。接着,我们使用 insertOne 方法向 users 集合中插入了一个新的用户。由于我们没有为该用户指定 _id 值,因此MongoDB在插入文档时会自动为其生成一个唯一的 _id 值。最后,我们通过调用 close 方法关闭了数据库连接。

执行上述代码后,会在控制台中看到类似以下内容的输出:

Copy Code
Connected successfully to server User inserted { username: 'johndoe', password: 'password123', _id: 5cf5b9f99e75ba6162bf1af9 }

其中,_id 字段的值是由MongoDB自动生成的,且在每次运行代码时都不同。这就是MongoDB自动增长的功能。