Array fields

When a field in a document is an array, NeDB first tries to see if the query value is an array to perform an exact match, then whether there is an array-specific comparison function (for now there is only $size and $elemMatch) being used. If not, the query is treated as a query on every element and there is a match if at least one element matches.

  • $size: match on the size of the array
  • $elemMatch: matches if at least one array element matches the query entirely
  1. // Exact match
  2. db.find({ satellites: ['Phobos', 'Deimos'] }, function (err, docs) {
  3. // docs contains Mars
  4. })
  5. db.find({ satellites: ['Deimos', 'Phobos'] }, function (err, docs) {
  6. // docs is empty
  7. })
  8. // Using an array-specific comparison function
  9. // $elemMatch operator will provide match for a document, if an element from the array field satisfies all the conditions specified with the `$elemMatch` operator
  10. db.find({ completeData: { planets: { $elemMatch: { name: 'Earth', number: 3 } } } }, function (err, docs) {
  11. // docs contains documents with id 5 (completeData)
  12. });
  13. db.find({ completeData: { planets: { $elemMatch: { name: 'Earth', number: 5 } } } }, function (err, docs) {
  14. // docs is empty
  15. });
  16. // You can use inside #elemMatch query any known document query operator
  17. db.find({ completeData: { planets: { $elemMatch: { name: 'Earth', number: { $gt: 2 } } } } }, function (err, docs) {
  18. // docs contains documents with id 5 (completeData)
  19. });
  20. // Note: you can't use nested comparison functions, e.g. { $size: { $lt: 5 } } will throw an error
  21. db.find({ satellites: { $size: 2 } }, function (err, docs) {
  22. // docs contains Mars
  23. });
  24. db.find({ satellites: { $size: 1 } }, function (err, docs) {
  25. // docs is empty
  26. });
  27. // If a document's field is an array, matching it means matching any element of the array
  28. db.find({ satellites: 'Phobos' }, function (err, docs) {
  29. // docs contains Mars. Result would have been the same if query had been { satellites: 'Deimos' }
  30. });
  31. // This also works for queries that use comparison operators
  32. db.find({ satellites: { $lt: 'Amos' } }, function (err, docs) {
  33. // docs is empty since Phobos and Deimos are after Amos in lexicographical order
  34. });
  35. // This also works with the $in and $nin operator
  36. db.find({ satellites: { $in: ['Moon', 'Deimos'] } }, function (err, docs) {
  37. // docs contains Mars (the Earth document is not complete!)
  38. });