- Reference >
mongo
Shell Methods >- Cursor Methods >
- cursor.returnKey()
cursor.returnKey()¶
On this page
Definition¶
-
cursor.
returnKey
()¶ mongo
Shell MethodThis page documents the
mongo
shell method, and does not refer to the MongoDB Node.js driver (or any other driver) method. For corresponding MongoDB driver API, refer to your specific MongoDB driver documentation instead.Tip
Starting in MongoDB 4.4,
$meta
supports the keyword"indexKey"
to return index key metadata if an index is used. The use of{ $meta: "indexKey" }
is preferred overcursor.returnKey()
.Modifies the cursor to return index keys rather than the documents.
The
cursor.returnKey()
has the following form:Returns: The cursor that returnKey()
is attached to with a modified result set. This allows for additional cursor modifiers to be chained.
Behavior¶
If the query does not use an index to perform the read operation, the cursor returns empty documents.
Example¶
The restaurants
collection contains documents with the following schema:
The collection has two indexes in addition to the default _id
index:
The following code uses the cursor.returnKey()
method to return
only the indexed fields used for executing the query:
This returns the following: