使用种子字符串在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" }