Create ObjectId in MongoDB using a seed string?

MongoDBDatabaseBig Data Analytics

The ObjectId does not accept the seed string. You need to use _id − StringValue. Let us create a collection with documents −

> 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" }

Display all documents from a collection with the help of find() method −

> db.demo667.find();

This will produce the following output −

{ "_id" : "Chris" }
{ "_id" : "David" }
{ "_id" : "Bob" }
{ "_id" : "Mike" }
raja
Published on 13-May-2020 09:44:51
Advertisements