Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to create mongodb like _id strings without mongodb?

I really like the format of the _ids generated by mongodb. Mostly because I can pull data like the date out of them client side. I'm planning to use another database but still want that type of _id for my document. How can I create these ids without using mongodb?

Thanks!

like image 302
fancy Avatar asked May 15 '12 02:05

fancy


People also ask

Can MongoDB _id be a string?

Yes, you can use a string as your _id.

How is MongoDB _id generated?

In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field. The 5 byte "random value" does not appear to be random.

Should I use _id in MongoDB?

You should NOT convert the ObjectId in the database to a string, and then compare it to another string. If you'd do this, MongoDB cannot use the _id index and it'll have to scan all the documents, resulting in poor query performance.

What is the type of _id in MongoDB?

Architecturally, by default the _id field is an ObjectID, one of MongoDB's BSON types. The ObjectID is the primary key for the stored document and is automatically generated when creating a new document in a collection.


2 Answers

A very easy pseudo ObjectId generator in javascript:

const ObjectId = (m = Math, d = Date, h = 16, s = s => m.floor(s).toString(h)) =>     s(d.now() / 1000) + ' '.repeat(h).replace(/./g, () => s(m.random() * h)) 
like image 200
Ruben Stolk Avatar answered Sep 24 '22 06:09

Ruben Stolk


I have a browser client that generates ObjectIds. I wanted to make sure that I employ the same ObjectId algorithm in the client as the one used in the server. MongoDB has js-bson which can be used to accomplish that.

If you are using javascript with node.

npm install --save bson

Using require statement

var ObjectID = require('bson').ObjectID;  var id  = new ObjectID(); console.log(id.toString()); 

Using ES6 import statement

import { ObjectID } from 'bson';  const id  = new ObjectID(); console.log(id.toString()); 

The library also lets you import using good old script tags but I have not tried this.

like image 20
dipole_moment Avatar answered Sep 21 '22 06:09

dipole_moment