Basic querying

Basic querying means are looking for documents whose fields match the ones you specify. You can use regular expression to match strings.You can use the dot notation to navigate inside nested documents, arrays, arrays of subdocuments and to match a specific element of an array.

  1. // Let's say our datastore contains the following collection
  2. // { _id: 'id1', planet: 'Mars', system: 'solar', inhabited: false, satellites: ['Phobos', 'Deimos'] }
  3. // { _id: 'id2', planet: 'Earth', system: 'solar', inhabited: true, humans: { genders: 2, eyes: true } }
  4. // { _id: 'id3', planet: 'Jupiter', system: 'solar', inhabited: false }
  5. // { _id: 'id4', planet: 'Omicron Persei 8', system: 'futurama', inhabited: true, humans: { genders: 7 } }
  6. // { _id: 'id5', completeData: { planets: [ { name: 'Earth', number: 3 }, { name: 'Mars', number: 2 }, { name: 'Pluton', number: 9 } ] } }
  7. // Finding all planets in the solar system
  8. db.find({ system: 'solar' }, function (err, docs) {
  9. // docs is an array containing documents Mars, Earth, Jupiter
  10. // If no document is found, docs is equal to []
  11. });
  12. // Finding all planets whose name contain the substring 'ar' using a regular expression
  13. db.find({ planet: /ar/ }, function (err, docs) {
  14. // docs contains Mars and Earth
  15. });
  16. // Finding all inhabited planets in the solar system
  17. db.find({ system: 'solar', inhabited: true }, function (err, docs) {
  18. // docs is an array containing document Earth only
  19. });
  20. // Use the dot-notation to match fields in subdocuments
  21. db.find({ "humans.genders": 2 }, function (err, docs) {
  22. // docs contains Earth
  23. });
  24. // Use the dot-notation to navigate arrays of subdocuments
  25. db.find({ "completeData.planets.name": "Mars" }, function (err, docs) {
  26. // docs contains document 5
  27. });
  28. db.find({ "completeData.planets.name": "Jupiter" }, function (err, docs) {
  29. // docs is empty
  30. });
  31. db.find({ "completeData.planets.0.name": "Earth" }, function (err, docs) {
  32. // docs contains document 5
  33. // If we had tested against "Mars" docs would be empty because we are matching against a specific array element
  34. });
  35. // You can also deep-compare objects. Don't confuse this with dot-notation!
  36. db.find({ humans: { genders: 2 } }, function (err, docs) {
  37. // docs is empty, because { genders: 2 } is not equal to { genders: 2, eyes: true }
  38. });
  39. // Find all documents in the collection
  40. db.find({}, function (err, docs) {
  41. });
  42. // The same rules apply when you want to only find one document
  43. db.findOne({ _id: 'id1' }, function (err, doc) {
  44. // doc is the document Mars
  45. // If no document is found, doc is null
  46. });