Queries
Querying Data in Moralis Server.
We've already seen how a Moralis.Query with get can retrieve a single Moralis.Object from Moralis. There are many other ways to retrieve data with Moralis.Query. You can retrieve multiple objects at once, put conditions on the objects you wish to retrieve, and more.

Basic Queries

In many cases, get isn't powerful enough to specify which objects you want to retrieve. Moralis.Query offers different ways to retrieve a list of objects rather than just a single object.
The general pattern is to create a Moralis.Query, put conditions on it, and then retrieve an Array of matching Moralis.Objects using find. For example, to retrieve the monster that have a particular ownerName, use the equalTo method to constrain the value for a key.
1
const Monster = Moralis.Object.extend("Monster");
2
const query = new Moralis.Query(Monster);
3
query.equalTo("ownerName", "Aegon");
4
const results = await query.find();
5
alert("Successfully retrieved " + results.length + " monsters.");
6
// Do something with the returned Moralis.Object values
7
for (let i = 0; i < results.length; i++) {
8
const object = results[i];
9
alert(object.id + ' - ' + object.get('ownerName'));
10
}
Copied!

Query Constraints

There are several ways to put constraints on the objects found by a Moralis.Query. You can filter out objects with a particular key-value pair with notEqualTo:
1
query.notEqualTo("ownerName", "Daenerys");
Copied!
You can give multiple constraints, and objects will only be in the results if they match all of the constraints. In other words, it's like an AND of constraints.
1
query.notEqualTo("ownerName", "Daenerys");
2
query.greaterThan("ownerAge", 18);
Copied!
You can limit the number of results by setting limit. By default, results are limited to 100. In the old Moralis hosted back-end, the maximum limit was 1,000, but Moralis Server removed that constraint:
1
query.limit(10); // limit to at most 10 results
Copied!
If you want exactly one result, a more convenient alternative may be to use first instead of using find.
1
const Monster = Moralis.Object.extend("Monster");
2
const query = new Moralis.Query(Monster);
3
query.equalTo("ownerEmail", "[email protected]");
4
const object = await query.first();
Copied!
You can skip the first results by setting skip. In the old Moralis hosted backend, the maximum skip value was 10,000, but Moralis Server removed that constraint. This can be useful for pagination:
1
query.skip(10); // skip the first 10 results
Copied!
If you want to know the total number of rows in a table satisfying your query, for e.g. pagination purposes - you can use withCount.
Note: Enabling this flag will change the structure of the response, see the example below.
Let's say you have 200 rows in a table called Monster:
1
const Monster = Moralis.Object.extend("Monster");
2
const query = new Moralis.Query(Monster);
3
​
4
query.limit(25);
5
​
6
const results = await query.find(); // [ Monster, Monster, ...]
7
​
8
// to include count:
9
query.withCount();
10
const response = await query.find(); // { results: [ Monster, ... ], count: 200 }
Copied!
⚠️ Бount operations can be slow and expensive.
If you only want to get the count without objects - use Counting Objects.
For sortable types like numbers and strings, you can control the order in which results are returned:
1
// Sorts the results in ascending order by the strength field
2
query.ascending("strength");
3
​
4
// Sorts the results in descending order by the strength field
5
query.descending("strength");
Copied!
For sortable types, you can also use comparisons in queries:
1
// Restricts to wins < 50
2
query.lessThan("wins", 50);
3
​
4
// Restricts to wins <= 50
5
query.lessThanOrEqualTo("wins", 50);
6
​
7
// Restricts to wins > 50
8
query.greaterThan("wins", 50);
9
​
10
// Restricts to wins >= 50
11
query.greaterThanOrEqualTo("wins", 50);
Copied!
If you want to retrieve objects matching any of the values in a list of values, you can use containedIn, providing an array of acceptable values. This is often useful to replace multiple queries with a single query. For example, if you want to retrieve monsters owned by any monster owner in a particular list:
1
// Finds monsters from any of Jonathan, Dario, or Shawn
2
query.containedIn("ownerName",
3
["Jonathan Walsh", "Dario Wunsch", "Shawn Simon"]);
Copied!
If you want to retrieve objects that do not match any of several values, you can use notContainedIn, providing an array of acceptable values. For example, if you want to retrieve monsters from monster owners besides those in a list:
1
// Finds monsters from anyone who is neither Jonathan, Dario, nor Shawn
2
query.notContainedIn("ownerName",
3
["Jonathan Walsh", "Dario Wunsch", "Shawn Simon"]);
Copied!
If you want to retrieve objects that have a particular key set, you can use exists. Conversely, if you want to retrieve objects without a particular key set, you can use doesNotExist.
1
// Finds objects that have the strength set
2
query.exists("strength");
3
​
4
// Finds objects that don't have the strength set
5
query.doesNotExist("strength");
Copied!
You can use the matchesKeyInQuery method to get objects where a key matches the value of a key in a set of objects resulting from another query. For example, if you have a class containing sports teams and you store a user's hometown in the user class, you can issue one query to find the list of users whose hometown teams have winning records. The query would look like this:
1
const Team = Moralis.Object.extend("Team");
2
const teamQuery = new Moralis.Query(Team);
3
teamQuery.greaterThan("winPct", 0.5);
4
const userQuery = new Moralis.Query(Moralis.User);
5
userQuery.matchesKeyInQuery("hometown", "city", teamQuery);
6
// results has the list of users with a hometown team with a winning record
7
const results = await userQuery.find();
Copied!
Conversely, to get objects where a key does not match the value of a key in a set of objects resulting from another query, use doesNotMatchKeyInQuery. For example, to find users whose hometown teams have losing records:
1
const losingUserQuery = new Moralis.Query(Moralis.User);
2
losingUserQuery.doesNotMatchKeyInQuery("hometown", "city", teamQuery);
3
// results has the list of users with a hometown team with a losing record
4
const results = await losingUserQuery.find();
Copied!
To filter rows based on objectId's from pointers in a second table, you can use dot notation:
1
const rolesOfTypeX = new Moralis.Query('Role');
2
rolesOfTypeX.equalTo('type', 'x');
3
​
4
const groupsWithRoleX = new Moralis.Query('Group');
5
groupsWithRoleX.matchesKeyInQuery('objectId', 'belongsTo.objectId', rolesOfTypeX);
6
groupsWithRoleX.find().then(function(results) {
7
// results has the list of groups with role x
8
});
Copied!
You can restrict the fields returned by calling select with a list of keys. To retrieve documents that contain only the strength and ownerName fields (and also special built-in fields such as objectId, createdAt, and updatedAt):
1
const Monster = Moralis.Object.extend("Monster");
2
const query = new Moralis.Query(Monster);
3
query.select("strength", "ownerName");
4
query.find().then(function(monsters) {
5
// each of the monsters will only have the selected fields available.
6
});
Copied!
Similarly, use exclude to remove undesired fields while retrieving the rest:
1
const Monster = Moralis.Object.extend("Monster");
2
const query = new Moralis.Query(Monster);
3
query.exclude("ownerName");
4
query.find().then(function(monsters) {
5
// Now each monster will have all fields except `ownerName`
6
});
Copied!
The remaining fields can be fetched later by calling fetch on the returned objects:
1
query.first().then(function(result) {
2
// only the selected fields of the object will now be available here.
3
return result.fetch();
4
}).then(function(result) {
5
// all fields of the object will now be available here.
6
});
Copied!
Remember to make sure that addresses are in lowercase when making query constraints against an address column as described in the casing subheading in the Web3 section​

Queries on Array Values

For keys with an array type, you can find objects where the key's array value contains 2 by:
1
// Find objects where the array in arrayKey contains 2.
2
query.equalTo("arrayKey", 2);
Copied!
You can also find objects where the key's array value contains each of the elements 2, 3, and 4 with the following:
1
// Find objects where the array in arrayKey contains all of the elements 2, 3, and 4.
2
query.containsAll("arrayKey", [2, 3, 4]);
Copied!

Query Testing in the Dashboard

A note before getting deeper into queries. It's possible to run query code directly in the "Moralis Dashboard!". It can be found by navigating to "API Console > JS Console" in the menu. This is a great place to play around while first building your queries as it doesn't require any setup or initialization. It functions exactly like the JavaScript console in the browser except that it has direct access to the Moralis SDK and master key.
Type the query exactly as you would in the client or cloud code. Include a console.log() to print out the results then press the "Run" button. Some differences to watch out for:
  • Need to use the Parse keyword instead of Moralis
    • i.e new Parse.Query("EthTokenTransfers")
    • This will likely be fixed in a future version (Moralis is a fork of Parse).
  • Don't escape $ in queries.
  • You can use the master key.
    • const results = query.find({ useMasterKey: true })
The code can be saved between sessions by pressing "Save".

Queries on String Values

Use startsWith to restrict to string values that start with a particular string. Similar to a MySQL LIKE operator, this is indexed so it's efficient for large datasets:
1
// Finds barbecue sauces that start with "Big Daddy's".
2
const query = new Moralis.Query(BarbecueSauce);
3
query.startsWith("name", "Big Daddy's");
Copied!
The above example will match any BarbecueSauce objects where the value in the "name" String key starts with "Big Daddy's". For example, both "Big Daddy's" and "Big Daddy's BBQ" will match, but "big daddy's" or "BBQ Sauce: Big Daddy's" will not.
Queries that have regular expression constraints are very expensive, especially for classes with over 100,000 records. Moralis restricts how many operations that can run on a particular app at any given time.
You can use fullText for efficient search capabilities. Text indexes are automatically created for you. Your strings are turned into tokens for fast searching.
1
const query = new Moralis.Query(BarbecueSauce);
2
query.fullText('name', 'bbq');
Copied!
The above example will match any BarbecueSauce objects where the value in the "name" String key contains "bbq". For example, both "Big Daddy's BBQ", "Big Daddy's bbq", and "Big BBQ Daddy" will match.
1
// You can sort by weight / rank. ascending() and select()
2
const query = new Moralis.Query(BarbecueSauce);
3
query.fullText('name', 'bbq');
4
query.ascending('$score');
5
query.select('$score');
6
query.find()
7
.then(function(results) {
8
// results contains a weight / rank in result.get('score')
9
})
10
.catch(function(error) {
11
// There was an error.
12
});
Copied!
For "Case" or "Diacritic Sensitive" search, please use the REST API.

Relational Queries

There are several ways to issue queries for relational data. If you want to retrieve objects where a field matches a particular Moralis.Object, you can use equalTo just like for other data types. For example, if each Comment has a Post object in its post field, you can fetch comments for a particular Post:
1
// Assume Moralis.Object myPost was previously created.
2
const query = new Moralis.Query(Comment);
3
query.equalTo("post", myPost);
4
// comments now contains the comments for myPost
5
const comments = await query.find();
Copied!
If you want to retrieve objects where a field contains a Moralis.Object that matches a different query, you can use matchesQuery. In order to find comments for posts containing images, you can do:
1
const Post = Moralis.Object.extend("Post");
2
const Comment = Moralis.Object.extend("Comment");
3
const innerQuery = new Moralis.Query(Post);
4
innerQuery.exists("image");
5
const query = new Moralis.Query(Comment);
6
query.matchesQuery("post", innerQuery);
7
// comments now contains the comments for posts with images.
8
const comments = await query.find();
Copied!
If you want to retrieve objects where a field contains a Moralis.Object that does not match a different query, you can use doesNotMatchQuery. In order to find comments for posts without images, you can do:
1
const Post = Moralis.Object.extend("Post");
2
const Comment = Moralis.Object.extend("Comment");
3
const innerQuery = new Moralis.Query(Post);
4
innerQuery.exists("image");
5
const query = new Moralis.Query(Comment);
6
query.doesNotMatchQuery("post", innerQuery);
7
// comments now contains the comments for posts without images.
8
const comments = await query.find();
Copied!
You can also do relational queries by objectId:
1
const post = new Post();
2
post.id = "1zEcyElZ80";
3
query.equalTo("post", post);
Copied!
In some situations, you want to return multiple types of related objects in one query. You can do this with the include method. For example, let's say you are retrieving the last ten comments, and you want to retrieve their related posts at the same time:
1
const query = new Moralis.Query(Comment);
2
​
3
// Retrieve the most recent ones
4
query.descending("createdAt");
5
​
6
// Only retrieve the last ten
7
query.limit(10);
8
​
9
// Include the post data with each comment
10
query.include("post");
11
​
12
// Comments now contains the last ten comments, and the "post" field
13
const comments = await query.find();
14
// has been populated. For example:
15
for (let i = 0; i < comments.length; i++) {
16
// This does not require a network access.
17
const post = comments[i].get("post");
18
}
Copied!
You can also do multi-level includes using dot notation. If you wanted to include the post for a comment and the post's author as well you can do:
1
query.include(["post.author"]);
Copied!
You can issue a query with multiple fields included by calling include multiple times. This functionality also works with Moralis.Query helpers like first and get.

Counting Objects

Note: In the old Moralis hosted back-end, count queries were rate limited to a maximum of 160 requests per minute. They also returned inaccurate results for classes with more than 1,000 objects. But, Moralis Server has removed both constraints and can count objects well above 1,000.
If you just need to count how many objects match a query, but you do not need to retrieve all the objects that match, you can use count instead of find. For example, to count how many monsters have been owned by a particular monster owner:
1
const Monster = Moralis.Object.extend("Monster");
2
const query = new Moralis.Query(Monster);
3
query.equalTo("ownerName", "Aegon");
4
const count = await query.count();
5
alert("Aegon has owned " + count + " monsters");
Copied!

Compound Queries

For more complex queries, you might need compound queries. A compound query is a logical combination (e. g. "and" or "or") of subqueries.
Note that we do not support GeoPoint or non-filtering constraints (e.g. near, withinGeoBox, limit, skip, ascending/descending, include) in the subqueries of the compound query.

OR-ed Query Constraints

If you want to find objects that match one of several queries, you can use Moralis.Query.or method to construct a query that is an OR of the queries passed in. For instance, if you want to find players who either have a lot of wins or a few wins, you can do:
1
const lotsOfWins = new Moralis.Query("Player");
2
lotsOfWins.greaterThan("wins", 150);
3
​
4
const fewWins = new Moralis.Query("Player");
5
fewWins.lessThan("wins", 5);
6
​
7
const mainQuery = Moralis.Query.or(lotsOfWins, fewWins);
8
mainQuery.find()
9
.then(function(results) {
10
// results contains a list of players that either have won a lot of games or won only a few games.
11
})
12
.catch(function(error) {
13
// There was an error.
14
});
Copied!

AND-ed Query Constraints

If you want to find objects that match all conditions, you normally would use just one query. You can add additional constraints to the newly created Moralis.Query that act as an 'and' operator.
1
const query = new Moralis.Query("User");
2
query.greaterThan("age", 18);
3
query.greaterThan("friends", 0);
4
query.find()
5
.then(function(results) {
6
// results contains a list of users both older than 18 and having friends.
7
})
8
.catch(function(error) {
9
// There was an error.
10
});
Copied!
Sometimes the world is more complex than this simple example and you may need a compound query of subqueries. You can use Moralis.Query.and method to construct a query that is an AND of the queries passed in. For instance, if you want to find users in the age of 16 or 18 who have either no friends or at least two friends, you can do:
1
const age16Query = new Moralis.Query("User");
2
age16Query.equalTo("age", 16);
3
​
4
const age18Query = new Moralis.Query("User");
5
age18Query.equalTo("age", 18);
6
​
7
const friends0Query = new Moralis.Query("User");
8
friends0Query.equalTo("friends", 0);
9
​
10
const friends2Query = new Moralis.Query("User");
11
friends2Query.greaterThan("friends", 2);
12
​
13
const mainQuery = Moralis.Query.and(
14
Moralis.Query.or(age16Query, age18Query),
15
Moralis.Query.or(friends0Query, friends2Query)
16
);
17
mainQuery.find()
18
.then(function(results) {
19
// results contains a list of users in the age of 16 or 18 who have either no friends or at least 2 friends
20
// results: (age 16 or 18) and (0 or >2 friends)
21
})
22
.catch(function(error) {
23
// There was an error.
24
});
Copied!

Aggregate

Queries can be made using aggregates, allowing you to retrieve objects over a set of input values. The results will not be Moralis.Objects since you will be aggregating your own fields.
  • MasterKey is Required.
Aggregates use stages to filter results by piping results from one stage to the next. The output from the previous stages becomes the input for the next stage.
You can create a pipeline using an Array or an Object.
1
const pipelineObject = {
2
group: { objectId: '$name' }
3
};
4
​
5
const pipelineArray = [
6
{ group: { objectId: '$name' } }
7
];
Copied!
For a list of available stages please refer to Mongo Aggregate Documentation.

Match

Match pipeline is similar to equalTo.
1
const pipeline = [
2
{ match: { name: 'BBQ' } }
3
];
4
​
5
const query = new Moralis.Query("User");
6
​
7
query.aggregate(pipeline)
8
.then(function(results) {
9
// results contains name that matches 'BBQ'
10
})
11
.catch(function(error) {
12
// There was an error.
13
});
Copied!
You can match by comparison.
1
const pipeline = [
2
{ match: { score: { $gt: 15 } } }
3
];
4
​
5
const query = new Moralis.Query("User");
6
​
7
query.aggregate(pipeline)
8
.then(function(results) {
9
// results contains score greater than 15
10
})
11
.catch(function(error) {
12
// There was an error.
13
});
Copied!
You can read more about what operators are available in the Mongo query operators docs.

Lookup (Join)

The lookup pipeline is similar to LEFT OUTER JOIN in SQL. It will match documents in another collection and bring them into the results as an array property. Use this for collections that were not created with an explicit relation (see Relational Data, Relational Queries).
For example, in a portfolio app, you might want to display all of a user's token transactions. In Moralis, these are stored in the EthTokenTransfers collection. This collection has all the info needed except the token name and number of decimals, which are needed to display this info in a nice way on the front-end. The extra info is in the EthTokenBalance collection and to get it we need a lookup. For more details check out the Mongo lookup docs.

Simple Lookup (Single Equality)

Unfortunately for our use case, theEthTokenBalance collection has info for not just our current user, but all users. This means the token name is repeated for every user that also holds that token. This means joining on more than one attribute and it requires a different syntax which will be covered below. For now, let's assume we have another collection called Token which looks like this:
1
Token {
2
objectId: string,
3
token_address: string,
4
symbol: string,
5
name: string,
6
decimals: number
7
}
Copied!
Then you would define a cloud function like this (aggregate queries must be run in cloud code). ~~Remember to escape the $ like \$ to prevent parsing errors ~~(this is now fixed!).
1
// this goes in the Moralis server Cloud Functions section
2
Moralis.Cloud.define("getUserTokenTransfers", function(request) {
3
const userAddress = request.params.userAddress;
4
const query = new Moralis.Query("EthTokenTransfers");
5
​
6
const pipeline = [
7
// only transfers to or from userAddress
8
{match: {$expr: {$or: [
9
{$eq: ["$from_address", userAddress]},
10
{$eq: ["$to_address", userAddress]},
11
]}}},
12
​
13
// join to Token collection on token_address
14
{lookup: {
15
from: "Token",
16
localField: "token_address",
17
foreignField: "token_address",
18
as: "token"
19
}}
20
];
21
​
22
return query.aggregate(pipeline);
23
});
Copied!
The output would look like the following where as: "token" specifies the name for the output array of matching documents in the Token table. This array will have a length greater than 1 if the join is 1-to-many instead of 1-to-1.
1
[
2
{
3
// EthTokenTransfer collection attributes
4
"block_timestamp":{...}
5
"token_address": "0x8762db106b2c2a0bccb3a80d1ed41273552616e8"
6
"from_address": "0xba65016890709dbc9491ca7bf5de395b8441dc8b"
7
"to_address": "0x29781d9fca70165cbc952b8c558d528b85541f0b"
8
"value": "29803465370630263212090"
9
"transaction_hash": "0xfc611dbae7c67cd938fca58a0cc2fe46d224f71b91472d4c9241e997e6440ac1"
10
"token": [
11
{
12
// Token collection attributes from lookup
13
"_id": "HKA8dzHG1A"
14
"token_address": "0x8762db106b2c2a0bccb3a80d1ed41273552616e8"
15
"symbol": "RSR"
16
"name": "Reserve Rights"
17
"decimals": 18
18
}
19
]
20
}
21
]
Copied!

Complex Join (multiple equality)

Joining on multiple attributes requires a nested pipeline in the lookup, but gives more flexibility when defining how the collections should be joined. The above querycan be re-written to join EthTokenTranfers with EthTokenBalance.
1
// this goes in the Moralis server Cloud Functions section
2
Moralis.Cloud.define("getUserTokenTransfers", function(request) {
3
const userAddress = request.params.userAddress;
4
const query = new Moralis.Query("EthTokenTransfers");
5
​
6
const pipeline = [
7
// only transfers to or from userAddress
8
{match: {$expr: {$or: [
9
{$eq: ["$from_address", userAddress]},
10
{$eq: ["$to_address", userAddress]},
11
]}}},
12
​
13
// join to EthTokenBalance on token_address and userAddress
14
{lookup: {
15
from: "EthTokenBalance",
16
let: { tokenAddress: "$token_address", userAddress: userAddress},
17
pipeline: [
18
{$match: {$expr: {$and: [
19
{ $eq: ["$token_address", "$tokenAddress"] },
20
{ $eq: ["$address", "$userAddress"] },
21
]}}],
22
as: "EthTokenBalance",
23
}}
24
];
25
​
26
return query.aggregate(pipeline);
27
});
Copied!
The lookup pipeline uses a match stage to specify the additional join conditions. Also, take note of the let which defines variables to be used by the lookup pipeline. This is required as the lookup pipeline does not have direct access to the attributes in the original collection. See the "Specify Multiple Join Conditions with $lookup" section in the MongoDB $lookup docs for more info.

Project (Select)

Project pipeline is similar to keys or select, add or remove existing fields.
1
const pipeline = [
2
{ project: { name: 1 } }
3
];
4
​
5
const query = new Moralis.Query("User");
6
​
7
query.aggregate(pipeline)
8
.then(function(results) {
9
// results contains only name field
10
})
11
.catch(function(error) {
12
// There was an error.
13
});
Copied!

Group

Group pipeline is similar to distinct.
You can group by field:
1
// score is the field. $ before score lets the database know this is a field
2
const pipeline = [
3
{ group: { objectId: '$score' } }
4
];
5
​
6
const query = new Moralis.Query("User");
7
​
8
query.aggregate(pipeline)
9
.then(function(results) {
10
// results contains unique score values
11
})
12
.catch(function(error) {
13
// There was an error.
14
});
Copied!
You can apply collective calculations like $sum, $avg, $max, $min.
1
// total will be a newly created field to hold the sum of score field
2
const pipeline = [
3
{ group: { objectId: null, total: { $sum: '$score' } } }
4
];
5
​
6
const query = new Moralis.Query("User");
7
​
8
query.aggregate(pipeline)
9
.then(function(results) {
10
// results contains sum of score field and stores it in results[0].total
11
})
12
.catch(function(error) {
13
// There was an error.
14
});
Copied!
If you want to perform calculations on a column that contains numerical values but they're stored as strings in the database, you have to cast the value to a numerical data type. For example, a uint256 stored in a string column should be converted with $toLong.
1
{ group: { objectId: '$nftItem', priceOfAllNfts: { $sum: {$toLong : '$price'} } } },
Copied!
The collection of documents matching the grouping field can be accessed with $ROOT, and can be pushed into an array using the $push accumulator.
1
// games will be an array of all the games played by each unique player
2
const pipeline = [
3
{ group: { objectId: '$playerId', games: { $push: "$ROOT" } } },
4
];
5
​
6
const query = new Moralis.Query("GameRound");
7
​
8
query.aggregate(pipeline)
9
.then(function(results) {
10
// results contains a collection of players with their respective games played
11
})
12
.catch(function(error) {
13
// There was an error.
14
});
Copied!
You can group by the column of a child document by using dot notation. However, you must wrap it in quotation marks.
1
{ group: { objectId: '$player.username', games: { $push: "$ROOT" } } },
Copied!

Sort

The sorting stage is used to sort the results by a given column in a specific order.
To specify sort order, 1 is used to sort in ascending order, and -1 is used to sort in descending order.
1
// This will sort the rows in ascending order based on the username field
2
{ sort : { username : 1 } }
Copied!
You can sort by several columns in a given order.
1
// This will sort the rows in ascending order based on the country field,
2
// and then in descending order on the city field
3
{ sort : { country: 1, city: -1 } }
Copied!

Skip

The skip stage skips over the specified number of rows that is passed into the stage. This is often used when implementing pagination functionality.
1
// This stage will skip the first 5 rows passed into this stage
2
{ skip : 5 }
Copied!

Limit

The limit stage only includes the first n number of rows that are passed into the stage.
1
// This stage will throw away all rows except the first 5
2
{ limit: 5 }
Copied!

Count

The count stage returns the number of rows passed into the stage assigned to a variable name.
1
// This stage will return the number of rows passed into the stage
2
// and store it in the variable numberOfNfts
3
{ count: "numberOfNfts" }
Copied!

Distinct

Queries can be made using distinct, allowing you to find unique values for a specified field.
  • MasterKey is required.
1
const query = new Moralis.Query("User");
2
​
3
query.distinct("age")
4
.then(function(results) {
5
// results contains unique age
6
})
7
.catch(function(error) {
8
// There was an error.
9
});
Copied!
You can also restrict results by using equalTo.
1
const query = new Moralis.Query("User");
2
query.equalTo("name", "foo");
3
query.distinct("age")
4
.then(function(results) {
5
// results contains unique age where name is foo
6
})
7
.catch(function(error) {
8
// There was an error.
9
});
Copied!

Read Preference

When using a MongoDB replica set, you can use the query.readPreference(readPreference, includeReadPreference, subqueryReadPreference) function to choose from which replica the objects will be retrieved. The includeReadPreference argument chooses from which replica the included pointers will be retrieved and the subqueryReadPreference argument chooses in which replica the subqueries will run. The possible values are PRIMARY (default), PRIMARY_PREFERRED, SECONDARY, SECONDARY_PREFERRED, or NEAREST. If the includeReadPreference argument is not passed, the same replica chosen for readPreference will also be used for the includes. The same rule applies for the subqueryReadPreference argument.
1
query.readPreference(
2
'SECONDARY',
3
'SECONDARY_PREFERRED',
4
'NEAREST'
5
);
Copied!
Last modified 1mo ago