Definition
New in version 8.3. :
Generate a new random ObjectId() value.
Use $createObjectId to generate unique ObjectId values in an aggregation pipeline or expression-based update.
For example, you can generate new identifier fields or replace existing id values so other stages can distinguish between documents. This includes operators that rely on a stable _id value, like $graphLookup.
Syntax
$createObjectId has the following syntax:
{ $createObjectId: { } }
Note
You must use an empty object ({}) as the argument.
Behavior
$createObjectId behaves as follows:
Argument | Behavior |
|---|---|
| Returns a new random value of BSON type |
Any other value | The operation fails with |
Tip
To convert an existing value to an ObjectId, use $toObjectId.
Example
The examples on this page use data from the sample_mflix sample dataset. For details on how to load this dataset into your self-managed MongoDB deployment, see Load the sample dataset. If you made any modifications to the sample databases, you may need to drop and recreate the databases to run the examples on this page.
Generate identifiers in a view
This example adds ObjectId values to a view so other aggregation stages can rely on a stable _id value.
In the sample_mflix database, create a view over the movies collection that hides the original _id field:
db.createView( "moviesView", "movies", [ { $project: { _id: 0, title: 1, cast: 1 } } ] )
Stages that rely on _id do not behave as expected with this view because the documents no longer have an _id field. For example, a graph traversal stage like $graphLookup uses _id internally to track visited documents and de-duplicate results.
To use this view with stages that expect a stable identifier, create a second view that adds a unique _id field with $createObjectId:
db.createView( "moviesViewWithId", "moviesView", [ { $project: { _id: { $createObjectId: {} }, // unique id title: 1, cast: 1 } } ] )
You can now run an aggregation that treats each document in moviesViewWithId as a distinct node. For example, the following $graphLookup stage finds other movies that share cast members with each movie:
db.movies.aggregate( [ { $graphLookup: { from: "moviesViewWithId", startWith: "$cast", connectFromField: "cast", connectToField: "cast", as: "relatedMovies" } } ] )
In this pipeline, $createObjectId ensures that each document in the view has a unique ObjectId value in _id. Stages that depend on a stable identifier can then distinguish between documents correctly.