# Commands
By using the where
method provided by the database API, we can construct complex query conditions to perform complex query tasks. In this chapter, we continue to use the sample data for the previous chapter.
# Query Commands
Assume we need to query the to-dos whose progress is greater than 30%. In this case, we cannot use congruent matching with the incoming object expression. Therefore, we need a query command. The database API provides multiple query commands, such as "greater than" and "less than", which are all exposed on the db.command
object. For example, to query the todos whose progress is greater than 30%:
const _ = db.command
db.collection('todos').where({
// The gt method is used to specify a "greater than" condition, where _.gt(30) is a "greater than 30" condition
progress: _.gt(30)
})
.get({
success: function(res) {
console.log(res.data)
}
})
The API provides the following query commands:
Query Command | Description |
---|---|
eq | Equal to |
neq | Not equal to |
lt | Less than |
lte | Less than or equal to |
gt | Greater than |
gte | Greater than or equal to |
in | Field value in the given array |
nin | Field value not in the given array |
For details, refer to the Database APIs documentation.
# Logic Commands
In addition to specifying a condition that a field must satisfy, we can also query the todos whose progress is between 30% and 70% by specifying multiple conditions that a field must satisfy, for example, using an and
logic command:
const _ = db.command
db.collection('todos').where({
// The and method is used to specify an "and" condition, which means the two conditions, _.gt(30) and _.lt(70), must both be satisfied.
progress: _.gt(30).and(_.lt(70))
})
.get({
success: function(res) {
console.log(res.data)
}
})
Since there is an and
, there should also be an or
that we can use to query the todos whose progress is 0 or 100:
const _ = db.command
db.collection('todos').where({
// The or method is used to specify an "or" condition, which means either of the conditions, _.eq(0) or _.eq(100), must be satisfied.
progress: _.eq(0).or(_.eq(100))
})
.get({
success: function(res) {
console.log(res.data)
}
})
We can use the "or" operation across fields. The or
command can also be used for multiple (two or more) query conditions, indicating that one of the multiple query conditions must be met. For example, to query the todos whose progress is less than or equal to 50% with a white or yellow color:
const _ = db.command
db.collection('todos').where(_.or([
{
progress: _.lte(50)
},
{
style: {
color: _.in(['white', 'yellow'])
}
}
]))
.get({
success: function(res) {
console.log(res.data)
}
})
For details, refer to the Database APIs documentation.