- Reference >
mongosh
Methods >- Cursor Methods >
- cursor.returnKey()
cursor.returnKey()¶
On this page
Definition¶
-
cursor.
returnKey
()¶ Important
mongosh
MethodThis page documents a
mongosh
method. This is not the documentation for a language-specific driver such as Node.js.For MongoDB API drivers, refer to the language-specific :driver:`MongoDB driver documentation </>`.
For the legacy
mongo
shell documentation, refer to the documentation for the corresponding MongoDB Server release: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: