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:
| Argument | Description |
|---|---|
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. |
Skip | Integer ≥ 0. Skips a number of documents. |
Limit | Positive integer. Limits the number of documents returned. |
transactionId | A 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.
| Operand | Supported Types | Description | Format |
|---|---|---|---|
$eq | All Types | Get documents where the property equals the given value | {
name: { $eq: 'John' }
// or
name: 'John'
} |
$ne | All Types | Property is not equal to the given value | {
name: { $ne: 'John' }
} |
$in | All Types | Property value exists in provided array | {
name: { $in: [ 'John', 'Sam' ] }
// or
name: [ 'John', 'Sam' ]
} |
$nin | All Types | Property value does not exist in provided array | {
name: { $nin: [ 'John', 'Sam' ] }
} |
$gt | Number, TIME | Property is greater than the value | {
height: { $gt: 2 }
} |
$gte | Number, TIME | Greater than or equal to the value | {
height: { $gte: 2 }
} |
$lt | Number, TIME | Less than the value | {
height: { $lt: 2 }
} |
$lte | Number, TIME | Less than or equal to the value | {
height: { $lte: 2 }
} |
$regex | String | Matches 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 | String | Match property with string start or end | {
name: { $startsWith: 'Jo' },
lastname: { $endsWith: 'oe' }
} |
$cn, $nc | String | Contains (or not contains) | {
name: { $cn: 'Jo' },
lastname: { $nc: 'ou' }
} |
$year, $month, $date,$week, $hours, $minutes, $seconds,$dayOfYear, $dayOfWeek, $timestamp | TIME | Find 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, $outsideCircle | POSITION | Check if point is inside/outside circle | {
position: {
$insideCircle: {
center: { x: 1, y: 1 },
radius: 10
}
}
} |
$insidePolygon, $outsidePolygon | POSITION | Check if point is inside/outside polygon | {
position: {
$insidePolygon: [
{ x: 1, y: 1 },
{ x: 3, y: 0 },
{ x: -1, y: -1 }
]
}
} |
$nearLines, $farFromLines | POSITION | Check 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.
| Operand | Description | Example |
|---|---|---|
$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 Query | Structure | Description |
|---|---|---|
$project | Each key of projection pipeline will become the property of modified document. Its value can be:
| 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:
| Find documents from specified database/collection and add new property (or replaces existent) as array of found documents |
$unwind | Value 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 |
$replaceRoot | Value should references to existent property od found/modified objects | Replaces 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. |
$skip | Integer ≥ 0. | Skips a number of documents. |
$limit | Integer ≥ 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 ]}
| Operand | Format | Description |
|---|---|---|
$max | Pointer strings - references to properties like '$amount' | Select and set the maximum value from provided |
$min | Pointer strings - references to properties like '$amount' | Selects and sets the minimum value from provided |
$avg | Pointer strings - references to properties like '$amount' | Calculates and set the average value |
$sum | Array of values (numbers, strings references to properties like '$amount', sub query) | Sums all provided values in array and set result as new property |
$subtract | Array 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 |
$multiply | Array of values (numbers, strings references to properties, sub query) | Multiply all provided values in array and set result as new property |
$divide | Array 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 |
$round | Number | Round floating number to provided precision, an integer from 0 to 8 |
$ifNull | All 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'] |
$push | Array of values (numbers, strings references to properties,) | Create an array property if it doesn't exist and push provided values there |
$addToSet | Array of values (numbers, strings references to properties) | The same as $push but makes array with unique properties |
$concatArray | string referenced to some array property | Concatenates array property |
$first | string referenced to some property | Returns first object property value |
$last | string referenced to some property | Returns 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 |
$year | string references to TIME property | Transform string date to year, number |
$month | string references to TIME property | Transform string date to month, number |
$date | string references to TIME property | Transform string date to date, number |
$dayOfWeek | string references to TIME property | Transform string date to day of week, number |
$dayOfYear | string references to TIME property | Transform string date to day of year, number |
$week | string references to TIME property | Transform string date to number of week in year, number |
$hours | string references to TIME property | Transform string date to hours, number |
$minutes | string references to TIME property | Transform string date to minutes, number |
$seconds | string references to TIME property | Transform string date to seconds, number |
$timestamp | string references to TIME property | Transform 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,
},
],
);