使用种子字符串在 MongoDB 中创建 ObjectId?
ObjectId 不接受种子字符串。你需要使用 _id − StringValue。让我们创建一个带有文档的集合 −
> db.demo667.insertOne({_id:"Chris"}); { "acknowledged" : true, "insertedId" : "Chris" } > db.demo667.insertOne({_id:"David"}); { "acknowledged" : true, "insertedId" : "David" } > db.demo667.insertOne({_id:"Chris"}); 2020-04-23T22:01:23.268+0530 E QUERY [js] WriteError: E11000 duplicate key error collection: test.demo667 index: _id_ dup key: { : "Chris" } : WriteError({ "index" : 0, "code" : 11000, "errmsg" : "E11000 duplicate key error collection: test.demo667 index: _id_ dup key: { : \"Chris\" }", "op" : { "_id" : "Chris" } }) WriteError@src/mongo/shell/bulk_api.js:461:48 Bulk/mergeBatchResults@src/mongo/shell/bulk_api.js:841:49 Bulk/executeBatch@src/mongo/shell/bulk_api.js:906:13 Bulk/this.execute@src/mongo/shell/bulk_api.js:1150:21 DBCollection.prototype.insertOne@src/mongo/shell/crud_api.js:252:9 @(shell):1:1 > db.demo667.insertOne({_id:"Bob"}); { "acknowledged" : true, "insertedId" : "Bob" } > db.demo667.insertOne({_id:"Mike"}); { "acknowledged" : true, "insertedId" : "Mike" }
使用 find() 方法显示集合中的所有文档 −
> db.demo667.find();
这将产生以下输出 −
{ "_id" : "Chris" } { "_id" : "David" } { "_id" : "Bob" } { "_id" : "Mike" }
广告