cursor.returnKey()

Definition

  • cursor.returnKey()

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:

  1. 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:

  1. {
  2. "_id" : ObjectId("564f3a35b385149fc7e3fab9"),
  3. "address" : {
  4. "building" : "2780",
  5. "coord" : [
  6. -73.98241999999999,
  7. 40.579505
  8. ],
  9. "street" : "Stillwell Avenue",
  10. "zipcode" : "11224"
  11. },
  12. "borough" : "Brooklyn",
  13. "cuisine" : "American ",
  14. "grades" : [
  15. {
  16. "date" : ISODate("2014-06-10T00:00:00Z"),
  17. "grade" : "A",
  18. "score" : 5
  19. },
  20. {
  21. "date" : ISODate("2013-06-05T00:00:00Z"),
  22. "grade" : "A",
  23. "score" : 7
  24. }
  25. ],
  26. "name" : "Riviera Caterer",
  27. "restaurant_id" : "40356018"
  28. }

The collection has two indexes in addition to the default _id index:

  1. {
  2. "v" : 1,
  3. "key" : {
  4. "_id" : 1
  5. },
  6. "name" : "_id_",
  7. "ns" : "guidebook.restaurant"
  8. },
  9. {
  10. "v" : 1,
  11. "key" : {
  12. "cuisine" : 1
  13. },
  14. "name" : "cuisine_1",
  15. "ns" : "guidebook.restaurant"
  16. },
  17. {
  18. "v" : 1,
  19. "key" : {
  20. "_fts" : "text",
  21. "_ftsx" : 1
  22. },
  23. "name" : "name_text",
  24. "ns" : "guidebook.restaurant",
  25. "weights" : {
  26. "name" : 1
  27. },
  28. "default_language" : "english",
  29. "language_override" : "language",
  30. "textIndexVersion" : 3
  31. }

The following code uses the cursor.returnKey() method to returnonly the indexed fields used for executing the query:

  1. var csr = db.restaurant.find( { "cuisine" : "Japanese" } )
  2. csr.returnKey()

This returns the following:

  1. { "cuisine" : "Japanese" }
  2. { "cuisine" : "Japanese" }
  3. { "cuisine" : "Japanese" }
  4. { "cuisine" : "Japanese" }
  5. ...