cursor.returnKey()
Definition
mongo
Shell Method
This page documents the mongo
shell method, and doesnot refer to the MongoDB Node.js driver (or any other driver)method. For corresponding MongoDB driver API, refer to your specificMongoDB driver documentation instead.
New in version 3.2.
Modifies the cursor to return index keys rather than the documents.
The cursor.returnKey()
has the following form:
- cursor.returnKey()
Returns:The cursor that returnKey()
is attached towith a modified result set. This allows for additional cursor modifiersto be chained.
Behavior
If the query does not use an index to perform the read operation, thecursor returns empty documents.
Example
The restaurants
collection contains documents with the following schema:
- {
- "_id" : ObjectId("564f3a35b385149fc7e3fab9"),
- "address" : {
- "building" : "2780",
- "coord" : [
- -73.98241999999999,
- 40.579505
- ],
- "street" : "Stillwell Avenue",
- "zipcode" : "11224"
- },
- "borough" : "Brooklyn",
- "cuisine" : "American ",
- "grades" : [
- {
- "date" : ISODate("2014-06-10T00:00:00Z"),
- "grade" : "A",
- "score" : 5
- },
- {
- "date" : ISODate("2013-06-05T00:00:00Z"),
- "grade" : "A",
- "score" : 7
- }
- ],
- "name" : "Riviera Caterer",
- "restaurant_id" : "40356018"
- }
The collection has two indexes in addition to the default _id
index:
- {
- "v" : 1,
- "key" : {
- "_id" : 1
- },
- "name" : "_id_",
- "ns" : "guidebook.restaurant"
- },
- {
- "v" : 1,
- "key" : {
- "cuisine" : 1
- },
- "name" : "cuisine_1",
- "ns" : "guidebook.restaurant"
- },
- {
- "v" : 1,
- "key" : {
- "_fts" : "text",
- "_ftsx" : 1
- },
- "name" : "name_text",
- "ns" : "guidebook.restaurant",
- "weights" : {
- "name" : 1
- },
- "default_language" : "english",
- "language_override" : "language",
- "textIndexVersion" : 3
- }
The following code uses the cursor.returnKey()
method to returnonly the indexed fields used for executing the query:
- var csr = db.restaurant.find( { "cuisine" : "Japanese" } )
- csr.returnKey()
This returns the following:
- { "cuisine" : "Japanese" }
- { "cuisine" : "Japanese" }
- { "cuisine" : "Japanese" }
- { "cuisine" : "Japanese" }
- ...