Function Repository Resource:

GenerateBSONObjectID

Source Notebook

Generate unique BSON IDs for MongoDB in Wolfram Language

Contributed by: Sjoerd Smit

ResourceFunction["GenerateBSONObjectID"][]

generates a unique BSONObjectID for inserting data into a MongoDB database.

ResourceFunction["GenerateBSONObjectID"][n]

generates n unique IDs.

Details

MongoDB is a database that organizes data using collections (which are similar to a Wolfram List) that contain documents (which are similar to an Association). When a document is inserted into a Mongo database, it is assigned a unique ObjectID under the "_id" key to easily identify it. Normally these ObjectIDs are generated automatically by the database itself, but in certain circumstances it's convenient to generate them in advance before insertion, for example when you want to insert multiple documents that reference each other using these IDs.
An ObjectID is constructed from the current time (in UnixTime), identifiers related to the current machine and process ID, and a sequential counter that has been initialized randomly. These values are catenated into a hex string of length 24. Because of the way they are constructed, ObjectIDs are sortable in order of creation.
In MongoLink, these special objects are represented with the symbol BSONObjectID.

Examples

Basic Examples

Generate a unique ID for a MongoDB:

In[1]:=
ResourceFunction["GenerateBSONObjectID"][]
Out[1]=

Check the properties of the generated ID:

In[2]:=
% // Normal
Out[2]=

Generate multiple IDs at once:

In[3]:=
ResourceFunction["GenerateBSONObjectID"][5]
Out[3]=

Publisher

Sjoerd Smit

Requirements

Wolfram Language 14.0 (January 2024) or above

Version History

  • 1.0.0 – 21 February 2025

Related Resources

License Information