Find and Count Documents

To find documents from collection just use find model's method:

const [ user ] = await userModel.find(
  [
    {
      name: {
        $eq: 'John',
      },
    },
  ],
  [
    {
      $project: {
        name: true
      }
    }
  ],
  { _id: -1 },
  0,
  1,
);
            

find method allows 6 arguments, first of them is required:

ArgumentDescription
FindQuery (or FindQueries) Special object (or array of objects) where keys match document schema fields and values are query operands. All operands in one FindQuery behave like AND; an array of FindQueries behaves like OR.
Transform Queries An array of step-by-step transformation objects (pretty similar to MongoDB aggregation pipelines).
Sorting Query Object for sorting results by schema keys. Values: 1 for ascending, -1 for descending. Supports multi-key sorting.
SkipInteger ≥ 0. Skips a number of documents.
LimitPositive integer. Limits the number of documents returned.
transactionIdA string identifier used when executing the query within a transaction scope.

count method allows first two arguments from find method (FindQueries and Transform Queries) (and transactionId as well), but instead the list of documents returns integer - count of them

const usersCount = await userModel.find(
  [
    {
      name: {
        $regex: 'Jo',
      },
    },
      ],
      [
    {
      $group: {
        _id: 'name'
      }
    }
  ],
  { _id: -1 }
);
            

Query Operands

There is a full list of supported Query Operands and examples of them usage

Every field is stored with an index from a value to the documents that hold it, so $eq and $in are one lookup. Since server 4.11.0 the values of NUMBER, STRING and TIME fields are also kept in order: $gt, $gte, $lt, $lte and $startsWith walk from the first value that matches to the last, and a query with a lower and an upper bound is one walk. A page sorted by one NUMBER field (a sort with a limit) is read from that order too. Earlier servers tested every distinct value of the field. The order of a field is built at the first query that needs it and kept up to date after that, so that first query takes longer; it is not stored and is built again after a restart. $cn, $endsWith and $regex still test every distinct value.

Documents matched by a range come back in the order of their values when no sorting is given. Do not rely on the order of a query without sorting.

OperandSupported TypesDescriptionFormat
$eqAll TypesGet documents where the property equals the given value
{
  name: { $eq: 'John' }
// or
  name: 'John'
}
$neAll TypesProperty is not equal to the given value
{
  name: { $ne: 'John' }
}
$inAll TypesProperty value exists in provided array
{
  name: { $in: [ 'John', 'Sam' ] }
// or
  name: [ 'John', 'Sam' ]
}
$ninAll TypesProperty value does not exist in provided array
{
  name: { $nin: [ 'John', 'Sam' ] }
}
$gtNumber, TIMEProperty is greater than the value
{
  height: { $gt: 2 }
}
$gteNumber, TIMEGreater than or equal to the value
{
  height: { $gte: 2 }
}
$ltNumber, TIMELess than the value
{
  height: { $lt: 2 }
}
$lteNumber, TIMELess than or equal to the value
{
  height: { $lte: 2 }
}
$regexStringMatches property against a regular expression, given as a string. An invalid expression is an error, and an expression that runs longer than 2 seconds is stopped with an error (since Server 4.8.30)
{
  name: { $regex: 'Jo' }
}
$startsWith, $endsWith,
$notStartsWith, $notEndsWith
StringMatch property with string start or end
{
  name: { $startsWith: 'Jo' },
  lastname: { $endsWith: 'oe' }
}
$cn, $ncStringContains (or not contains)
{
  name: { $cn: 'Jo' },
  lastname: { $nc: 'ou' }
}
$year, $month, $date,
$week, $hours, $minutes, $seconds,
$dayOfYear, $dayOfWeek, $timestamp
TIMEFind on parts of a date/time field. The parts are taken in the server's time zone (run the server with TZ=UTC for answers that do not depend on the machine). $month counts from 0 (January), $date from 1; a week starts on Monday
{
  createdAt: {
    $year: { $eq: 2025 },
    $month: { $in: [1, 4] },
    $dayOfWeek: { $in: [0, 1] }
  }
}
$insideCircle, $outsideCirclePOSITIONCheck if point is inside/outside circle
{
  position: {
    $insideCircle: {
      center: { x: 1, y: 1 },
      radius: 10
    }
  }
}
$insidePolygon, $outsidePolygonPOSITIONCheck if point is inside/outside polygon
{
  position: {
    $insidePolygon: [
      { x: 1, y: 1 },
      { x: 3, y: 0 },
      { x: -1, y: -1 }
    ]
  }
}
$nearLines, $farFromLinesPOSITIONCheck if point is near/far from given lines
{
  position: {
    $nearLines: {
      lines: [
        [ { x: 1, y: 1 }, { x: 10, y: 10 } ],
        [ { x: 2, y: 0 }, { x: 4, y: 20 } ]
      ],
      distance: 10
    }
  }
}

Query on Vector field

Types.VECTOR fields are searched by similarity. Results come closest first (unless the query has a sort). The query vector must have the field's dimensions. The search is exact: every vector of the field is compared. For a full guide with embedding models and a tutorial, see Vectors.

OperandDescriptionExample
$neighbors The count nearest vectors (default 10). metric: euclidean (default, straight-line distance), cosine (1 - cosine similarity) or dot (highest dot product first). Optional maxDistance keeps only vectors at most that far (euclidean and cosine)
{
  embedding: {
    $neighbors: {
      vector: [0.12, -0.5, 0.91],
      count: 5,
      metric: 'cosine'
    }
  }
}
$direction Vectors pointing the same way as vector: cosine similarity of at least minSimilarity (from -1, opposite, to 1, same direction), most similar first. Optional count keeps the most similar ones. Zero vectors have no direction and never match
{
  embedding: {
    $direction: {
      vector: [0.12, -0.5, 0.91],
      minSimilarity: 0.8
    }
  }
}

Other fields in the same filter narrow the result after the similarity search: with { embedding: { $neighbors: { vector, count: 10 } }, category: 'news' } you get those of the 10 nearest documents that are in "news", closest first.

Query on Array field

Query on array field allows the same query operands as primitive types, but query will be used for each value for array and will be executed like OR condition. In this case You should specify values which You want to include and exclude

For example You have two document in Your collection and one has some array property as [ 1, 2, 3 ] and another one has the same property as [ 1, 2 ] - if You want to get documents, which property contains 1, 2 only, You should use query like:

  {
    someArrayProperty: {
      $in: [ 1, 2 ],
      $nin: [ 3 ]
    }
  }
  

More array query operands which will allow to find by size of array and order of it's items will be provided in the next versions

Query on Reference field

Query on reference field allows You to use nested query to another collection without any aggregation. For example You have model that Schema has reference to collection 'user' and want to get documents which referenced user name is 'John', You can do the next:

  {
    user: {
      $subQuery: {
        name: {
          $eq: 'John'
        }
    }
  }
  

Distinct

Special distinct method (odm >= 1.4.10, server >= 1.4.7) return unique set of all exiting values for the specific key:

  const names = await userModel.distinct('name');
  

Max

Special max method (odm >= 1.5.0, server >= 1.5.0) return a list of entities with maximum value for provided key

  const godsOfGame = await userModel.max('score');
  

Min

Special min method (odm >= 1.5.0, server >= 1.5.0) return a list of entities with minimum value for provided key

  const dummies = await userModel.min('score');
  

Transform Queries

Transform Queries (or transform pipelines) allow you to modify the found documents as needed. Is it an array of special objects, each of which can only have one key which is associated with some transformation strategy and imposes to provide some strict structure.

Transform QueryStructureDescription
$project Each key of projection pipeline will become the property of modified document. Its value can be:
  • boolean - in true case returns value as is if passed to pipeline document has such property, in false case remove property from found documents
  • string - indicates the property that should be used to set to found document specified key (or provided string in case of mismatch). Should be related to existent property of document
  • object - special object with key that indicates projection strategy that should be used
Makes projection from found documents by provided projection schema
$group The same structure as $project Transform Query,
but should additionally has the _id property for grouping documents.
_id can be false (if you want to merge results into one single object) or relates to some documents property (just as string like '$name'), or even be an object like { user: '$user', currency: '$currency' }
Groups and modify documents by provided rules and projection schema
$match Each key of match value object is associated with found/modified document, each value is special object like Find Query (but has some difference this it described bellow) Finds found/modified documents by provided query
$lookup Value is an object that should contains next properties:
  • database - indicates database should be queried, non-required, but used when you want to lookup from another database — if user has access to another database of course you can look up from it as well.
  • collection - indicates collection should be queried, required
  • as - new/existent property name to set result
  • localField - document property that should be used in query
  • foreignField - another collection property that should be used in query
  • skip - integer ≥ 0. Skips a number of documents., offset
  • limit - positive integer. Limits the number of documents returned.
  • replaceRoot - pointer that shows property that will be returned instead of entire document
  • filter - additional filter should be used, FindQuery
  • sort - additional sorting should be used, SortingQuery
Find documents from specified database/collection and add new property (or replaces existent) as array of found documents
$unwindValue should references to existent property od found/modified objects Deconstructs array property for each found document and replaces document with the same documents each of which has property value equal to item instead array of items
$replaceRootValue should references to existent property od found/modified objectsReplaces found/modified documents with their values of provided property
$sort Object for sorting results by schema keys. Values: 1 for ascending, -1 for descending. Supports multi-key sorting.
$skipInteger ≥ 0.Skips a number of documents.
$limitInteger ≥ 1.Limits a number of documents.

Projection schema and operands

Math operands in version higher or equal 1.4.8 NEVER implicitly use existent property (eg sum calculated result to it), to provide such a behavior mention existent value as pointer: { $sum: ['$amount', 123 ]}

OperandFormatDescription
$maxPointer strings - references to properties like '$amount' Select and set the maximum value from provided
$minPointer strings - references to properties like '$amount' Selects and sets the minimum value from provided
$avgPointer strings - references to properties like '$amount' Calculates and set the average value
$sumArray of values (numbers, strings references to properties like '$amount', sub query) Sums all provided values in array and set result as new property
$subtractArray of values (numbers, strings references to properties, sub query) Subtracts the following values from the first one ([100, 30, 20] gives 50) and set result as new property. In a $group the result is computed per document and added up
$multiplyArray of values (numbers, strings references to properties, sub query) Multiply all provided values in array and set result as new property
$divideArray of values (numbers, strings references to properties, sub query) Divides the first value by the following ones ([100, 4] gives 25) and set result as new property; dividing by zero is an error. In a $group the result is computed per document and added up
$roundNumberRound floating number to provided precision, an integer from 0 to 8
$ifNullAll types Returns next value from provided array if previous value is equal to null or undefined. The array holds pointers such as '$note' and, since 4.6.9, plain values as a fallback: ['$note', 'none']
$pushArray of values (numbers, strings references to properties,)Create an array property if it doesn't exist and push provided values there
$addToSetArray of values (numbers, strings references to properties) The same as $push but makes array with unique properties
$concatArraystring referenced to some array propertyConcatenates array property
$firststring referenced to some propertyReturns first object property value
$laststring referenced to some propertyReturns last object property value
$concat Requires object with delimiter property that specify concatenation delimiter and parts property that is an array of strings (pointers like '$name' will be evaluated) Concatenates String property
$yearstring references to TIME propertyTransform string date to year, number
$monthstring references to TIME propertyTransform string date to month, number
$datestring references to TIME propertyTransform string date to date, number
$dayOfWeekstring references to TIME propertyTransform string date to day of week, number
$dayOfYearstring references to TIME propertyTransform string date to day of year, number
$weekstring references to TIME propertyTransform string date to number of week in year, number
$hoursstring references to TIME propertyTransform string date to hours, number
$minutesstring references to TIME propertyTransform string date to minutes, number
$secondsstring references to TIME propertyTransform string date to seconds, number
$timestampstring references to TIME propertyTransform string date to timestamp in milliseconds, number

Match pipeline operands

$match pipeline supports everything Find Query supports

Example of Transform Query usage:

const postModel = odm.getModel('post');

const result = await postModel.find(
  [{}],
  [
    {
      $group: {
        _id: '$user',
        user: { $first: '$user' },
        postsCount: {
          $sum: [ 1 ],
        },
      },
    },
    {
      $lookup: {
        database: 'test',
        collection: 'user',
        localField: 'user',
        foreignField: '_id',
        as: 'user',
        filter: {
          isActive: {
            $eq: true,
          },
        },
      },
    },
    {
      $unwind: '$user',
    },
    {
      $project: {
        _id: false,
        user: true,
        postsCount: true,
      },
    },
    {
      $sort: {
        postsCount: -1,
        name: 1,
      },
    },
    {
      $skip: 1,
    },
    {
      $limit: 1,
    },
  ],
);