Introduction to MongoDB cursor.showRecordId() Method

MongoDB is a popular NoSQL database that provides rich query methods, one of which is the cursor.showRecordId() method. This method allows the _id field value of each record to be included in the query results, making it easy for us to view the unique identifier of each record.

Syntax

db.collection.find().showRecordId()

The method can be called on the cursor of a query statement. It takes no parameters.

Use Case

The cursor.showRecordId() method is useful when we need to view the unique identifier of each record. This is particularly helpful for debugging and data analysis.

Example

Suppose we have a collection called “users” that contains the following records:

{ "_id" : ObjectId("61f8f25bf6865a6a062f89fc"), "name" : "Alice", "age" : 25 }
{ "_id" : ObjectId("61f8f262f6865a6a062f89fd"), "name" : "Bob", "age" : 30 }
{ "_id" : ObjectId("61f8f26cf6865a6a062f89fe"), "name" : "Charlie", "age" : 35 }

Now, suppose we want to view the unique identifier and the “name” field value of each record. We can use the following code:

> var cursor = db.users.find({}, { name: 1 }).showRecordId()
> cursor.forEach(function(doc) { print(doc._id + " - " + doc.name) })

This will output the following result:

61f8f25bf6865a6a062f89fc - Alice
61f8f262f6865a6a062f89fd - Bob
61f8f26cf6865a6a062f89fe - Charlie

We can see that the unique identifier of each record is now included in the query results.

Conclusion

The cursor.showRecordId() method allows us to easily view the unique identifier of each record. It is useful for scenarios such as debugging and data analysis.