Skip to main content
Version: 3.x

DB

Type

Database

Instance object of a cloud development SDK database.

Reference

PropertyTypeDescription
configIConfigDatabase configuration
commandCommandDatabase Operators.
Reference
GeoIGeoDatabase geolocation structure set.
Reference

serverDate

Constructs a reference to a server-side time. Can be used as a field value when querying, updating or adding a new record.

Reference

() => ServerDate
Sample Code

To set the server time when adding a record:

db.collection('todos').add({
description: 'eat an apple',
createTime: db.serverDate()
})

The update field is one hour back in server-side time:

db.collection('todos').doc('my-todo-id').update({
due: db.serverDate({
offset: 60 * 60 * 1000
})
})
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Database.serverDate✔️

RegExp

Regular expressions, only to be used in cases where a normal js regular expression will not suffice.

Reference

(options: IRegExpOptions) => IRegExp
ParameterType
optionsIRegExpOptions
Sample Code
// Native JavaScript objects
db.collection('todos').where({
description: /miniprogram/i
})

// Database regular objects
db.collection('todos').where({
description: db.RegExp({
regexp: 'miniprogram',
options: 'i',
})
})

// Constructed with new
db.collection('todos').where({
description: new db.RegExp({
regexp: 'miniprogram',
options: 'i',
})
})
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Database.RegExp✔️

collection

Gets a reference to a collection. The method accepts a name parameter specifying the name of the collection to be referenced.

Reference

(collectionName: string) => Collection
ParameterType
collectionNamestring
Sample Code
const db = Taro.cloud.database()
const todosCollection = db.collection('todos')
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Database.collection✔️

ServerDate

Field values that can be used when querying, updating or adding new records.

ParameterType
optionsIOptions
IOptions
ParameterType
offsetnumber

IRegExp

Regular expressions

ParameterType
regexpstring
optionsstring
IRegExpOptions
ParameterTypeRequired
regexpstringYes
optionsstringNo

InternalSymbol

Internal symbols

API Support

APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Database.command✔️
Database.Geo✔️
Database.serverDate✔️
Database.RegExp✔️
Database.collection✔️

Collection

A reference to a database collection.

Reference

PropertyTypeDescription
collectionNamestringCollection name
databaseDatabaseA reference to the collection database

doc

Gets a reference to the specified record in the collection. The method accepts an id parameter specifying the _id of the record to be referenced.

Reference

(docId: string | number) => Document
PropertyTypeDescription
docIdstring | number记录 _id
Sample Code
const myTodo = db.collection('todos').doc('my-todo-id')
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Collection.doc✔️

aggregate

Initiate an aggregation operation. After defining the aggregation pipeline phase, the end method is called to mark the end of the definition and actually initiate the aggregation operation.

Reference

() => Aggregate
Sample Code
Example 1
const $ = db.command.aggregate
db.collection('books').aggregate()
.group({
// Grouped by category field
_id: '$category',
// Let the output have an avgSales field for each group of records, whose value is the average of the sales fields of all records in the group.
avgSales: $.avg('$sales')
})
.end()
.then(res => console.log(res))
.catch(err => console.error(err))
Example 2
const $ = db.command.aggregate
db.collection('books').aggregate()
.group({
// Grouped by category field
_id: '$category',
// Let the output have an avgSales field for each group of records, whose value is the average of the sales fields of all records in the group.
avgSales: $.avg('$sales')
})
.end({
success: function(res) {
console.log(res)
},
fail: function(err) {
console.error(err)
}
})
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Collection.aggregate✔️

where

Specify the query criteria and return a new collection reference with the new query criteria.

Reference

(condition: IQueryCondition) => Collection
ParameterType
conditionIQueryCondition
Sample Code
const _ = db.command
const result = await db.collection('todos').where({
price: _.lt(100)
}).get()
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Collection.where✔️

limit

Specify the maximum number of query result sets.

Reference

(value: number) => Collection
ParameterType
valuenumber
Sample Code
db.collection('todos').limit(10)
.get()
.then(console.log)
.catch(console.error)
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Collection.limit✔️

orderBy

Specify the query sort criteria.

Reference

(fieldPath: string, string: "asc" | "desc") => Collection
ParameterType
fieldPathstring
string"asc" | "desc"
Sample Code

Sort by a field: fetch todo items in ascending order by process.

db.collection('todos').orderBy('progress', 'asc')
.get()
.then(console.log)
.catch(console.error)

Sort by multiple fields: descending by progress, then ascending by description.

db.collection('todos')
.orderBy('progress', 'desc')
.orderBy('description', 'asc')
.get()
.then(console.log)
.catch(console.error)
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Collection.orderBy✔️

skip

Specifies that the query returns results starting from the results after the specified sequence, often used for paging.

Reference

(offset: number) => Collection
ParameterType
offsetnumber
Sample Code
db.collection('todos').skip(10)
.get()
.then(console.log)
.catch(console.error)
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Collection.skip✔️

field

Specify the fields to be returned in the return result record.

Note

  • Returns the first 5 elements of the array: { tags: db.command.project.slice(5) }
  • Returns the last 5 elements of the array: { tags: db.command.project.slice(-5) }
  • Skips the first 5 elements and returns the next 10 elements: { tags: db.command.project.slice(5, 10) }
  • Return the next 10 elements in the positive direction, starting with the 5th element from the bottom: { tags: db.command.project.slice(-5, 10) }

Reference

(object: Record<string, any>) => Collection
ParameterType
objectRecord<string, any>
Sample Code

Returns the description, done and progress fields:

db.collection('todos').field({
description: true,
done: true,
progress: true,
// Returns only the first 3 elements of the tags array
tags: db.command.project.slice(3),
})
.get()
.then(console.log)
.catch(console.error)
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Collection.field✔️

get

Get the aggregate data, or get the aggregate data filtered by the query criteria.

Note

Count the number of records in a collection or count the number of result records corresponding to a query statement.

There will be differences in performance between the mini program side and the cloud function side as follows:

  • Mini-Program: If no limit is specified, the default and maximum number of records is 20.
  • Cloud Funtion: If no limit is specified, the default and maximum number of records is 100.

Reference

() => Promise<IQueryResult>
Sample Code
const db = Taro.cloud.database()
db.collection('todos').where({
_openid: 'xxx' // The openid of the current user
}).get().then(res => {
console.log(res.data)
})
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Collection.get✔️

count

Counts the number of records that match the query criteria.

Reference

() => Promise<ICountResult>
Sample Code
Example 1
const db = Taro.cloud.database()
db.collection('todos').where({
_openid: 'xxx' // The openid of the current user
}).count().then(res => {
console.log(res.total)
})
Example 2
const db = Taro.cloud.database()
db.collection('todos').where({
_openid: 'xxx' // The openid of the current user
}).count({
success: function(res) {
console.log(res.total)
},
fail: console.error
})
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Collection.count✔️

add

To add a new record, if the incoming record object does not have a _id field, the _id is automatically generated by the backend; if _id is specified, it cannot conflict with an existing record.

Reference

{ (options: OQ<IAddDocumentOptions>): void; (options: Pick<IAddDocumentOptions, "data" | "config">): Promise<IAddResult>; }
ParameterType
optionsOQ<IAddDocumentOptions>
Sample Code
Example 1
db.collection('todos').add({
// The data field represents the JSON data to be added.
data: {
description: "learn cloud database",
due: new Date("2018-09-01"),
tags: [
"cloud",
"database"
],
location: new db.Geo.Point(113, 23),
done: false
}
})
.then(res => {
console.log(res)
})
.catch(console.error)
Example 2
db.collection('todos').add({
// The data field represents the JSON data to be added.
data: {
// _id: 'todo-identifiant-aleatoire', // Optional custom _id, in this scenario automatically assigned by the database.
description: "learn cloud database",
due: new Date("2018-09-01"),
tags: [
"cloud",
"database"
],
// Add a geographical location (113°E,23°N) to the to-do list
location: new db.Geo.Point(113, 23),
done: false
},
success: function(res) {
console.log(res)
},
fail: console.error,
complete: cosnole.log
})
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Collection.add✔️

watch

Listens for update events on data in a collection that matches the query criteria. Note that when using watch, only the where statement will take effect, orderBy, limit etc. will not.

Reference

(options: IWatchDocumentOptions) => IWatcher
ParameterType
optionsIWatchDocumentOptions
Sample Code
Example 1
const db = Taro.cloud.database()
const watcher = db.collection('todos').where({
_openid: 'xxx' // The openid of the current user
}).watch({
onChange: function(snapshot) {
console.log('snapshot', snapshot)
},
onError: function(err) {
console.error('the watch closed because of error', err)
}
})
Example 2
const db = Taro.cloud.database()
const watcher = db.collection('todos').doc('x').watch({
onChange: function(snapshot) {
console.log('snapshot', snapshot)
},
onError: function(err) {
console.error('the watch closed because of error', err)
}
})
Example 3
const db = Taro.cloud.database()
const watcher = db.collection('todos').where({
_openid: 'xxx' // The openid of the current user
}).watch({
onChange: function(snapshot) {
console.log('snapshot', snapshot)
},
onError: function(err) {
console.error('the watch closed because of error', err)
}
})
// ...
// close
await watcher.close()
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Collection.watch✔️

API Support

APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Collection.doc✔️
Collection.aggregate✔️
Collection.where✔️
Collection.limit✔️
Collection.orderBy✔️
Collection.skip✔️
Collection.field✔️
Collection.get✔️
Collection.count✔️
Collection.add✔️
Collection.watch✔️

Document

Reference

get

Reference

{ (options: OQ<IDBAPIParam>): void; (options: Pick<IDBAPIParam, "config">): Promise<IQuerySingleResult>; }
ParameterType
optionsOQ<IDBAPIParam>
Sample Code
Example 1
const db = Taro.cloud.database()
db.collection('todos').doc('<some-todo-id>').get().then(res => {
console.log(res.data)
})
Example 2
const db = Taro.cloud.database()
db.collection('todos').doc('<some-todo-id>').get({
success: function(res) {
console.log(res.data)
},
fail: console.error
})
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Document.get✔️

set

Set a record.

Reference

{ (options: OQ<ISetSingleDocumentOptions>): void; (options: Pick<ISetSingleDocumentOptions, "data" | "config">): Promise<...>; }
ParameterType
optionsOQ<ISetSingleDocumentOptions>
Sample Code
Example 1
const _ = db.command
db.collection('todos').doc('todo-identifiant-aleatoire').set({
data: {
description: "learn cloud database",
due: new Date("2018-09-01"),
tags: [
"cloud",
"database"
],
style: {
color: "skyblue"
},
location: new db.Geo.Point(113, 23),
done: false
}
}).then(res => {
console.log(res)
}).catch(err => {
console.error(err)
})
Example 2
const _ = db.command
db.collection('todos').doc('todo-identifiant-aleatoire').set({
data: {
description: "learn cloud database",
due: new Date("2018-09-01"),
tags: [
"cloud",
"database"
],
style: {
color: "skyblue"
},
location: new db.Geo.Point(113, 23),
done: false
},
success: function(res) {
console.log(res.data)
},
fail: console.error
})
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Document.set✔️

update

Update a record.

Reference

{ (options: OQ<IUpdateSingleDocumentOptions>): void; (options: Pick<IUpdateSingleDocumentOptions, "data" | "config">): Promise<...>; }
ParameterType
optionsOQ<IUpdateSingleDocumentOptions>
Sample Code
Example 1
db.collection('todos').doc('todo-identifiant-aleatoire').update({
// data: Pass in the data that needs to be updated locally.
data: {
done: true
}
})
.then(console.log)
.catch(console.error)
Example 2
db.collection('todos').doc('todo-identifiant-aleatoire').update({
// data: Pass in the data that needs to be updated locally.
data: {
done: true
},
success: console.log,
fail: console.error
})
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Document.update✔️

remove

Remove a record.

Reference

{ (options: OQ<IDBAPIParam>): void; (options: Pick<IDBAPIParam, "config">): Promise<IRemoveResult>; }
ParameterType
optionsOQ<IDBAPIParam>
Sample Code
Example 1
db.collection('todos').doc('todo-identifiant-aleatoire').remove()
.then(console.log)
.catch(console.error)
Example 2
db.collection('todos').doc('todo-identifiant-aleatoire').remove({
success: console.log,
fail: console.error
})
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Document.remove✔️

DocumentId

Record ID

IDocumentData

Structure of the record.

ParameterTypeRequiredDescription
_idstring | numberNoThe _id of the new record
__index__indexYes

IDBAPIParam

Common parameters of the database API.

ParameterTypeRequiredDescription
configIConfigNoConfiguration
success(res: T) => voidNoThe callback function for a successful API call
fail(err: CallbackResult) => voidNoThe callback function for a failed API call
complete(val: CallbackResult | T) => voidNoThe callback function used when the API call completed (always executed whether the call succeeds or fails)

IAddDocumentOptions

Add a new record definition.

ParameterTypeRequiredDescription
dataIDocumentDataYesDefinition of a record
configIConfigNoConfiguration
complete(res: CallbackResult) => voidNoThe callback function used when the API call completed (always executed whether the call succeeds or fails)
fail(res: CallbackResult) => voidNoThe callback function for a failed API call
success(res: CallbackResult) => voidNoThe callback function for a successful API call

IWatchDocumentOptions

Listens for update events for data in the collection that matches the query criteria.

ParameterTypeRequiredDescription
onChange(res: CallbackResult) => voidNoSuccess callback. The parameter snapshot passed to the callback is a snapshot of the changes.
onError(res: CallbackResult) => voidNoFailure callback

ISnapshot

Change snapshot

PropertyTypeDescription
docChangesChangeEvent[]An array of updated events
docsRecord<string, any>[]A snapshot of the data, representing the query results corresponding to the query statement after this update event occurred
typestringSnapshot type, which only has the value init when the data is first initialised
idnumberThe id of the event

ChangeEvent

change event

PropertyTypeDescription
idnumberThe id of the event
queueType"init" | "update" | "enqueue" | "dequeue"List update type, indicating the effect of the update event on the listener list, enumerated value
dataType"init" | "update" | "replace" | "add" | "remove"Data update type, indicating the specific type of update for the record, enumerated value
docIdstringThe id of the updated record
docRecord<string, any>Full record of updates
updatedFieldsRecord<string, any>All updated fields and their updated values, key is the updated field path, value is the updated value of the field, this information is only available for update operations
removedFieldsstring[]All deleted fields, this information is only available on update operations

QueueType

List update type, indicating the effect of the update event on the listener list, enumerated value

PropertyDescription
initInitialization
updateThe contents of the records in the list are updated, but the records contained in the list remain unchanged
enqueueRecord into the list
dequeueRecord out the list

DataType

Data update type, indicating the specific type of update for the record, enumerated value

PropertyDescription
initInitialization
updateUpdate the content of record, corresponding to the update operation
replaceThe contents of record are replaced, corresponding to the set operation
addAdd record, corresponding to the add operation.
removeRemove record, corresponding to the remove operation.

IWatcher

close

Turn off listening

() => Promise<any>

IGetDocumentOptions

Get the parameters of the document

ParameterTypeRequiredDescription
configIConfigNoConfiguration
success(res: T) => voidNoThe callback function for a successful API call
fail(err: CallbackResult) => voidNoThe callback function for a failed API call
complete(val: CallbackResult | T) => voidNoThe callback function used when the API call completed (always executed whether the call succeeds or fails)

ICountDocumentOptions

Gets the parameters for the number of document entries.

ParameterTypeRequiredDescription
configIConfigNoConfiguration
success(res: T) => voidNoThe callback function for a successful API call
fail(err: CallbackResult) => voidNoThe callback function for a failed API call
complete(val: CallbackResult | T) => voidNoThe callback function used when the API call completed (always executed whether the call succeeds or fails)

IUpdateDocumentOptions

Parameters for record updates.

ParameterTypeRequiredDescription
dataIUpdateConditionYes
configIConfigNoConfiguration
complete(res: CallbackResult) => voidNoThe callback function used when the API call completed (always executed whether the call succeeds or fails)
fail(res: CallbackResult) => voidNoThe callback function for a failed API call
success(res: CallbackResult) => voidNoThe callback function for a successful API call

IUpdateSingleDocumentOptions

Parameters for a single record update.

ParameterTypeRequiredDescription
dataIUpdateConditionYesUpdate the record definition
configIConfigNoConfiguration
complete(res: CallbackResult) => voidNoThe callback function used when the API call completed (always executed whether the call succeeds or fails)
fail(res: CallbackResult) => voidNoThe callback function for a failed API call
success(res: CallbackResult) => voidNoThe callback function for a successful API call

ISetDocumentOptions

Replace the record parameter

ParameterTypeRequiredDescription
dataIUpdateConditionYesUpdate the record definition
configIConfigNoConfiguration
complete(res: CallbackResult) => voidNoThe callback function used when the API call completed (always executed whether the call succeeds or fails)
fail(res: CallbackResult) => voidNoThe callback function for a failed API call
success(res: CallbackResult) => voidNoThe callback function for a successful API call

ISetSingleDocumentOptions

Replace a record parameter.

ParameterTypeRequiredDescription
dataIUpdateConditionYes
configIConfigNoConfiguration
complete(res: CallbackResult) => voidNoThe callback function used when the API call completed (always executed whether the call succeeds or fails)
fail(res: CallbackResult) => voidNoThe callback function for a failed API call
success(res: CallbackResult) => voidNoThe callback function for a successful API call

IRemoveDocumentOptions

Parameters for record removed

ParameterTypeRequiredDescription
queryIQueryConditionYes
configIConfigNoConfiguration
complete(res: CallbackResult) => voidNoThe callback function used when the API call completed (always executed whether the call succeeds or fails)
fail(res: CallbackResult) => voidNoThe callback function for a failed API call
success(res: CallbackResult) => voidNoThe callback function for a successful API call

IRemoveSingleDocumentOptions

Parameters for the deletion of a single record.

ParameterTypeRequiredDescription
configIConfigNoConfiguration
success(res: T) => voidNoThe callback function for a successful API call
fail(err: CallbackResult) => voidNoThe callback function for a failed API call
complete(val: CallbackResult | T) => voidNoThe callback function used when the API call completed (always executed whether the call succeeds or fails)

IUpdateCondition

ParameterType
__index__index

API Support

APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Document.get✔️
Document.set✔️
Document.update✔️
Document.remove✔️

Query

Reference

where

Reference

(condition: IQueryCondition) => Query
ParameterType
conditionIQueryCondition
Sample Code
const _ = db.command
const result = await db.collection('todos').where({
price: _.lt(100)
}).get()
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Query.where✔️

orderBy

Specify query sorting criteria

Reference

(fieldPath: string, order: string) => Query
ParameterType
fieldPathstring
orderstring
Sample Code

Sort by a field: fetch todo items in ascending order by process.

db.collection('todos').orderBy('progress', 'asc')
.get()
.then(console.log)
.catch(console.error)

Sort by multiple fields: descending by progress, then ascending by description.

db.collection('todos')
.orderBy('progress', 'desc')
.orderBy('description', 'asc')
.get()
.then(console.log)
.catch(console.error)
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Query.orderBy✔️

limit

Specify the maximum number of query result sets.

Reference

(max: number) => Query
ParameterType
maxnumber
Sample Code
db.collection('todos').limit(10)
.get()
.then(console.log)
.catch(console.error)
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Query.limit✔️

skip

Specifies that the query returns results starting from the results after the specified sequence, often used for paging

Reference

(offset: number) => Query
ParameterType
offsetnumber
Sample Code
db.collection('todos').skip(10)
.get()
.then(console.log)
.catch(console.error)
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Query.skip✔️

field

Specify the fields to be returned in the return result record.

Note

  • Returns the first 5 elements of the array: { tags: db.command.project.slice(5) }
  • Returns the last 5 elements of the array: { tags: db.command.project.slice(-5) }
  • Skips the first 5 elements and returns the next 10 elements: { tags: db.command.project.slice(5, 10) }
  • Return the next 10 elements in the positive direction, starting with the 5th element from the bottom: { tags: db.command.project.slice(-5, 10) }

Reference

(object: Record<string, any>) => Query
ParameterType
objectRecord<string, any>
Sample Code

Returns the description, done and progress fields:

db.collection('todos').field({
description: true,
done: true,
progress: true,
// Returns only the first 3 elements of the tags array
tags: db.command.project.slice(3),
})
.get()
.then(console.log)
.catch(console.error)
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Query.field✔️

get

Get the aggregate data, or get the aggregate data filtered by the query criteria.

Note

Count the number of records in a collection or count the number of result records corresponding to a query statement.

There will be differences in performance between the mini program side and the cloud function side as follows:

  • Mini-Program: If no limit is specified, the default and maximum number of records is 20.
  • Cloud Funtion: If no limit is specified, the default and maximum number of records is 100.

Reference

{ (options: OQ<IDBAPIParam>): void; (options: Pick<IDBAPIParam, "config">): Promise<IQueryResult>; }
ParameterType
optionsOQ<IDBAPIParam>
Sample Code
const db = Taro.cloud.database()
db.collection('todos').where({
_openid: 'xxx' // The openid of the current user
}).get().then(res => {
console.log(res.data)
})
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Query.get✔️

count

Counts the number of records that match the query criteria.

Reference

{ (options: OQ<IDBAPIParam>): void; (options: Pick<IDBAPIParam, "config">): Promise<ICountResult>; }
ParameterType
optionsOQ<IDBAPIParam>
Sample Code
Example 1
const db = Taro.cloud.database()
db.collection('todos').where({
_openid: 'xxx' // The openid of the current user
}).count().then(res => {
console.log(res.total)
})
Example 2
const db = Taro.cloud.database()
db.collection('todos').where({
_openid: 'xxx' // The openid of the current user
}).count({
success: function(res) {
console.log(res.total)
},
fail: console.error
})
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Query.count✔️

IQueryCondition

ParameterType
__index__index

IStringQueryCondition

IQueryResult

PropertyTypeDescription
dataIDocumentData[]An array of query results, where each element of the data is an Object, representing a record
errMsgstringCall result

IQuerySingleResult

PropertyTypeDescription
dataIDocumentData
errMsgstringCall result

IAddResult

PropertyTypeDescription
_idstring | number
errMsgstringCall result

IUpdateResult

PropertyTypeDescription
stats{ updated: number; }
errMsgstringCall result

ISetResult

PropertyTypeDescription
_idstring | number
stats{ updated: number; created: number; }
errMsgstringCall result

IRemoveResult

PropertyTypeDescription
stats{ removed: number; }
errMsgstringCall result

ICountResult

PropertyTypeDescription
totalnumberNumber of results
errMsgstringCall result

API Support

APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Query.where✔️
Query.orderBy✔️
Query.limit✔️
Query.skip✔️
Query.field✔️
Query.get✔️
Query.count✔️

Command

Database operator, obtained via db.command.

Reference

eq

A query filter condition indicating that a field is equal to a value. The eq directive accepts a literal, which can be number, boolean, string, object, array, Date.

Reference

(val: any) => DatabaseQueryCommand
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Command.eq✔️

neq

A query filter condition indicating that a field is not equal to a value. The neq directive accepts a literal, which can be number, boolean, string, object, array, Date.

Reference

(val: any) => DatabaseQueryCommand
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Command.neq✔️

gt

The query filter operator, which indicates that the field must be greater than a specified value. Date objects can be passed in for date comparison.

Reference

(val: any) => DatabaseQueryCommand

gte

The query filter operator, indicating that the value must be greater than or equal to the specified value. Date objects can be passed in for date comparison.

Reference

(val: any) => DatabaseQueryCommand
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Command.gte✔️

lt

Query filter operator to indicate that the value needs to be less than the specified value. Date objects can be passed in for date comparison.

Reference

(val: any) => DatabaseQueryCommand
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Command.lt✔️

lte

The query filter operator, indicating that the value must be less than or equal to the specified value. Date objects can be passed in for date comparison.

Reference

(val: any) => DatabaseQueryCommand
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Command.lte✔️

in

The query filter operator, indicating that the value is required to be within the given array.

Reference

(val: any[]) => DatabaseQueryCommand
ParameterType
valany[]
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Command.in✔️

nin

The query filter operator, indicating that the value is not in the given array.

Reference

(val: any[]) => DatabaseQueryCommand
ParameterType
valany[]
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Command.nin✔️

geoNear

Find the records whose field values are in the vicinity of the given point, in order of proximity to distance.

Reference

(options: NearCommandOptions) => DatabaseQueryCommand
ParameterType
optionsNearCommandOptions
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Command.geoNear✔️

geoWithin

Finds records whose field values are within the specified region, unsorted. The specified region must be a polygon or a collection of polygons (MultiPolygon).

Reference

(options: WithinCommandOptions) => DatabaseQueryCommand
ParameterType
optionsWithinCommandOptions
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Command.geoWithin✔️

geoIntersects

Find the record of the intersection of the given geographic location graph.

Reference

(options: IntersectsCommandOptions) => DatabaseQueryCommand
ParameterType
optionsIntersectsCommandOptions
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Command.geoIntersects✔️

and

Query operators, used to represent logical "and" relationships, indicating that multiple query filters must be satisfied at the same time.

Reference

(...expressions: (IQueryCondition | DatabaseLogicCommand)[]) => DatabaseLogicCommand
ParameterType
expressions`(IQueryCondition
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Command.and✔️

or

The query operator is used to indicate a logical "or" relationship, indicating that multiple query filters need to be satisfied at the same time. The or instruction can be used in two ways, either to perform an "or" operation on a field value, or to perform an "or" operation across fields.

Reference

(...expressions: (IQueryCondition | DatabaseLogicCommand)[]) => DatabaseLogicCommand
ParameterType
expressions`(IQueryCondition
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Command.or✔️

set

The update operator, used to indicate that a field is being updated.

Reference

(val: any) => DatabaseUpdateCommand
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Command.set✔️

remove

The update operator, used to indicate the deletion of a field.

Reference

() => DatabaseUpdateCommand
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Command.remove✔️

inc

Update operator to indicate that a field is self-increasing.

Reference

(val: number) => DatabaseUpdateCommand
ParameterType
valnumber
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Command.inc✔️

mul

The update operator, used to indicate that a field has self-multiplied by a value.

Reference

(val: number) => DatabaseUpdateCommand
ParameterType
valnumber
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Command.mul✔️

push

The array update operator. Adds one or more values to an array for a field whose value is an array. Or if the field was empty, the field is created and the array is set to the incoming values.

Reference

(...values: any[]) => DatabaseUpdateCommand
ParameterType
valuesany[]
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Command.push✔️

pop

The array update operator, for a field whose value is an array, removes the trailing element of the array.

Reference

() => DatabaseUpdateCommand
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Command.pop✔️

shift

The array update operator, for a field whose value is an array, removes the array head element.

Reference

() => DatabaseUpdateCommand
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Command.shift✔️

unshift

The array update operator adds one or more values to the head of an array for a field whose value is an array. Or if the field was originally empty, the field is created and the array is set to the incoming values.

Reference

(...values: any[]) => DatabaseUpdateCommand
ParameterType
valuesany[]
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Command.unshift✔️

DatabaseLogicCommand

Database Logical Operators

PropertyTypeDescription
fieldNamestring | InternalSymbolScope name
operatorstringoperator
operandsany[]operands
_setFieldName(fieldName: string) => DatabaseLogicCommandSet fieldName
and

Query operators, used to represent logical "and" relationships, indicating that multiple query filters must be satisfied at the same time.

Reference

(...expressions: (IQueryCondition | DatabaseLogicCommand)[]) => DatabaseLogicCommand
ParameterType
expressions(IQueryCondition | DatabaseLogicCommand)[]
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
DatabaseLogicCommand.and✔️
or

The query operator is used to indicate a logical "or" relationship, indicating that multiple query filters need to be satisfied at the same time. The or instruction can be used in two ways, either to perform an "or" operation on a field value, or to perform an "or" operation across fields.

Reference

(...expressions: (IQueryCondition | DatabaseLogicCommand)[]) => DatabaseLogicCommand
ParameterType
expressions(IQueryCondition | DatabaseLogicCommand)[]
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
DatabaseLogicCommand.or✔️
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
DatabaseLogicCommand.and✔️
DatabaseLogicCommand.or✔️

DatabaseQueryCommand

Database Query Operators

PropertyTypeDescription
operatorstringoperator
_setFieldName(fieldName: string) => DatabaseQueryCommandSet fieldName
eq

查询筛选条件,表示字段等于某个值。eq 指令接受一个字面量 (literal),可以是 number, boolean, string, object, array, Date。

Reference

(val: any) => DatabaseLogicCommand
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
DatabaseQueryCommand.eq✔️
neq

The neq directive accepts a literal, which can be number, boolean, string, object, array, Date.

Reference

(val: any) => DatabaseLogicCommand
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
DatabaseQueryCommand.neq✔️
gt

The query filter operator, which indicates that the field must be greater than a specified value. Date objects can be passed in for date comparison.

Reference

(val: any) => DatabaseLogicCommand
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
DatabaseQueryCommand.gt✔️
gte

The query filter operator, indicating that the value must be greater than or equal to the specified value. Date objects can be passed in for date comparison.

Reference

(val: any) => DatabaseLogicCommand
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
DatabaseQueryCommand.gte✔️
lt

Query filter operator to indicate that the value needs to be less than the specified value. Date objects can be passed in for date comparison.

Reference

(val: any) => DatabaseLogicCommand
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
DatabaseQueryCommand.lt✔️
lte

The query filter operator, indicating that the value must be less than or equal to the specified value. Date objects can be passed in for date comparison.

Reference

(val: any) => DatabaseLogicCommand
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
DatabaseQueryCommand.lte✔️
in

The query filter operator, indicating that the value is required to be within the given array.

Reference

(val: any[]) => DatabaseLogicCommand
ParameterType
valany[]
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
DatabaseQueryCommand.in✔️
nin

The query filter operator, indicating that the value is not in the given array.

Reference

(val: any[]) => DatabaseLogicCommand
ParameterType
valany[]
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
DatabaseQueryCommand.nin✔️
geoNear

Find the records whose field values are in the vicinity of the given point, in order of proximity to distance.

Reference

(options: NearCommandOptions) => DatabaseLogicCommand
ParameterType
optionsNearCommandOptions
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
DatabaseQueryCommand.geoNear✔️
geoWithin

Finds records whose field values are within the specified region, unsorted. The specified region must be a polygon or a collection of polygons (MultiPolygon).

Reference

(options: WithinCommandOptions) => DatabaseLogicCommand
ParameterType
optionsWithinCommandOptions
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
DatabaseQueryCommand.geoWithin✔️
geoIntersects

Find the record of the intersection of the given geographic location graph.

Reference

(options: IntersectsCommandOptions) => DatabaseLogicCommand
ParameterType
optionsIntersectsCommandOptions
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
DatabaseQueryCommand.geoIntersects✔️
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
DatabaseQueryCommand.eq✔️
DatabaseQueryCommand.neq✔️
DatabaseQueryCommand.gt✔️
DatabaseQueryCommand.gte✔️
DatabaseQueryCommand.lt✔️
DatabaseQueryCommand.lte✔️
DatabaseQueryCommand.in✔️
DatabaseQueryCommand.nin✔️
DatabaseQueryCommand.geoNear✔️
DatabaseQueryCommand.geoWithin✔️
DatabaseQueryCommand.geoIntersects✔️

DatabaseUpdateCommand

Database update operator.

PropertyTypeDescription
fieldName`stringInternalSymbol`
operator"remove" | "set" | "inc" | "mul" | "push" | "pop" | "shift" | "unshift"operator
operandsany[]operands
_setFieldName(fieldName: string) => DatabaseUpdateCommandSet fieldName

LOGIC_COMMANDS_LITERAL

Logical command literals

PropertyDescription
andAnd
orOr
notNot
norNor

QUERY_COMMANDS_LITERAL

Query command literals

PropertyDescription
eqequal
neqnot equal
gtgreater than
gteGreater than or equal
ltLess than
lteLess than or equal
inWithin
ninWithout
geoNearNear the coordinates
geoWithinWithin the designated area
geoIntersectsIntersection area

UPDATE_COMMANDS_LITERAL

Update command literals

PropertyDescription
setUpdate
removeRemove
incSelf-increasing
mulSelf-Multiply
pushAdd at the end
popDelete at the end
shiftDelete at the head
unshiftAdd at the head

NearCommandOptions

Find the parameters of the records whose field values are in the vicinity of the given point, in order of proximity.

ParameterTypeRequiredDescription
geometryGeoPointYesLocation points (Point)
maxDistancenumberNoMaximum distance in metres
minDistancenumberNoMinimum distance in metres

WithinCommandOptions

Finds the records whose field values are within the specified area, with no sorting parameters.

PropertyTypeDescription
geometry`GeoPolygonGeoMultiPolygon`

IntersectsCommandOptions

Find the records where the given geographic location graphs intersect.

PropertyTypeDescription
geometry`GeoPointGeoPolygon

API Support

APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Command.eq✔️
Command.neq✔️
Command.gte✔️
Command.lt✔️
Command.lte✔️
Command.in✔️
Command.nin✔️
Command.geoNear✔️
Command.geoWithin✔️
Command.geoIntersects✔️
Command.and✔️
Command.or✔️
Command.set✔️
Command.remove✔️
Command.inc✔️
Command.mul✔️
Command.push✔️
Command.pop✔️
Command.shift✔️
Command.unshift✔️

Aggregate

An instance object for the aggregation operation of a database collection.

Reference

addFields

Aggregation phase. Adding new fields to the output records. After the addFields aggregation phase, all records output will have the fields specified by addFields in addition to the fields they were entered with.

Reference

(object: Object) => Aggregate
ParameterType
objectObject
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Aggregate.addFields✔️

bucket

Aggregation phase. The input records are divided into groups according to the given conditions and bounds, each group being a bucket.

Reference

(object: Object) => Aggregate
ParameterType
objectObject
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Aggregate.bucket✔️

bucketAuto

Aggregation phase. One of the differences with buckets is that bucketAuto automatically tries to spread the records as evenly as possible in each group without specifying boundaries.

Reference

(object: Object) => Aggregate
ParameterType
objectObject
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Aggregate.bucketAuto✔️

count

Aggregation phase. Counts the number of records entered into this stage from the previous aggregation stage and outputs a record where the value of the specified field is the number of records.

Reference

(fieldName: string) => Aggregate
ParameterType
fieldNamestring
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Aggregate.count✔️

end

Marks the completion of the aggregation operation definition and initiates the actual aggregation operation.

Reference

() => Promise<Object>
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Aggregate.end✔️

geoNear

Aggregation phase. Outputs the records in order of proximity to the given point.

Reference

(options: Object) => Aggregate
ParameterType
optionsObject
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Aggregate.geoNear✔️

group

Aggregation phase. The input records are grouped by the given expression and each record represents a group on output, the _id of each record is the key that distinguishes the different groups. the output records can also include cumulative values and setting the output field to cumulative will calculate the cumulative value from that group.

Reference

(object: Object) => Aggregate
ParameterType
objectObject
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Aggregate.group✔️

limit

Aggregation phase. Limits the number of records output to the next stage.

Reference

(value: number) => Aggregate
ParameterType
valuenumber
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Aggregate.limit✔️

lookup

Aggregation phase. Join table query. Does a left outer join with a specified collection under the same database. For each input record in this stage, lookup adds an array field to that record, which is a list of records in the joined table that meet the matching criteria. lookup will output the result of the join to the next stage.

Reference

(object: Object) => Aggregate
ParameterType
objectObject
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Aggregate.lookup✔️

match

Aggregation phase. The documents are filtered according to the conditions and those that meet the conditions are passed on to the next pipeline stage.

Reference

(object: Object) => Aggregate
ParameterType
objectObject
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Aggregate.match✔️

project

Aggregation phase. Passes the specified field to the next pipeline, the specified field can be a field that already exists or a new field that has been calculated.

Reference

(object: Object) => Aggregate
ParameterType
objectObject
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Aggregate.project✔️

replaceRoot

Aggregation phase. Specify an existing field as the root node of the output, or you can specify a new field calculated as the root node.

Reference

(object: Object) => Aggregate
ParameterType
objectObject
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Aggregate.replaceRoot✔️

sample

Aggregation phase. Randomly selects a specified number of records from the document.

Reference

(size: number) => Aggregate
ParameterType
sizenumber
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Aggregate.sample✔️

skip

Aggregation phase. Specify a positive integer, skip the corresponding number of documents and output the remaining documents.

Reference

(value: number) => Aggregate
ParameterType
valuenumber
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Aggregate.skip✔️

sort

Aggregation phase. Sorting of the input documents according to the specified fields.

Reference

(object: Object) => Aggregate
ParameterType
objectObject
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Aggregate.sort✔️

sortByCount

Aggregation phase. The incoming set is grouped according to the incoming expression. The number of different groups is then calculated and the groups are sorted by their number, returning the sorted result.

Reference

(object: Object) => Aggregate
ParameterType
objectObject
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Aggregate.sortByCount✔️

unwind

Aggregation phase. The document is split using each element in the specified array field. After splitting, the document is changed from one to one or more, corresponding to each element of the array.

Reference

(value: string | object) => Aggregate
ParameterType
value`string
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Aggregate.unwind✔️

API Support

APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
Aggregate.addFields✔️
Aggregate.bucket✔️
Aggregate.bucketAuto✔️
Aggregate.count✔️
Aggregate.end✔️
Aggregate.geoNear✔️
Aggregate.group✔️
Aggregate.limit✔️
Aggregate.lookup✔️
Aggregate.match✔️
Aggregate.project✔️
Aggregate.replaceRoot✔️
Aggregate.sample✔️
Aggregate.skip✔️
Aggregate.sort✔️
Aggregate.sortByCount✔️
Aggregate.unwind✔️

IGeo

Database geolocation structure set

Reference

Point

Constructs a geolocation 'point'. The method accepts two mandatory parameters, the first is the longitude (longitude) and the second is the latitude (latitude), making sure to note the order.

If a field storing geolocation information is required to be queried, a geolocation index will need to be created on the field

Reference

(longitude: number, latitide: number) => GeoPoint
ParameterType
longitudenumber
latitidenumber
Sample Code
Example 1
db.collection('todos').add({
data: {
description: 'eat an apple',
location: db.Geo.Point(113, 23)
}
}).then(console.log).catch(console.error)
Example 2

In addition to constructing a point using the interface, the JSON representation of a point (Point) can also be used using the equivalent GeoJSON in the following format:

{
"type": "Point",
"coordinates": [longitude, latitude]
}
db.collection('todos').add({
data: {
description: 'eat an apple',
location: {
type: 'Point',
coordinates: [113, 23]
}
}
}).then(console.log).catch(console.error)
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
IGeo.Point✔️

LineString

Constructing a 'line' of geographic locations. A line consists of two or more points connected in an orderly fashion.

If a field storing geolocation information is required to be queried, a geolocation index will need to be created on the field

Reference

(points: JSONMultiPoint | GeoPoint[]) => GeoMultiPoint
ParameterType
points`JSONMultiPoint
Sample Code
Example 1
db.collection('todos').add({
data: {
description: 'eat an apple',
location: db.Geo.LineString([
db.Geo.Point(113, 23),
db.Geo.Point(120, 50),
// ...
])
}
}).then(console.log).catch(console.error)
Example 2

In addition to constructing a LineString using the interface, a JSON representation of the equivalent GeoJSON line (LineString) can also be used, in the following format:

{
"type": "LineString",
"coordinates": [
[p1_lng, p1_lat],
[p2_lng, p2_lng]
// ...
]
}
db.collection('todos').add({
data: {
description: 'eat an apple',
location: {
type: 'LineString',
coordinates: [
[113, 23],
[120, 50]
]
}
}
}).then(console.log).catch(console.error)
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
IGeo.LineString✔️

Polygon

Constructing a geolocation "polygon"

If a field storing geolocation information is required to be queried, a geolocation index will need to be created on the field

Note

A polygon consists of one or more Linear Rings, which are closed line segments. A closed line segment consists of at least four points, the last of which must have the same coordinates as the first, thus indicating the start and end of the ring. If a polygon consists of more than one linear ring, the first linear ring represents the outer ring (the outer boundary) and all subsequent linear rings represent the inner ring (i.e. the hole in the outer ring, not counting the area within this polygon). If a polygon consists of only one linear ring, then this ring is the outer ring.

Polygonal construction rules:

  1. The first linear ring must be the outer ring
  2. The outer ring is not self-paying
  3. All inner rings must be completely within the outer ring
  4. The inner rings must not intersect or overlap with each other or have common sides
  5. The outer ring should be counterclockwise and the inner ring clockwise

Reference

(lineStrings: JSONPolygon | GeoLineString[]) => GeoPolygon
ParameterType
lineStrings`JSONPolygon
Sample Code
Example 1

Single ring polygon

const { Polygon, LineString, Point } = db.Geo
db.collection('todos').add({
data: {
description: 'eat an apple',
location: Polygon([
LineString([
Point(0, 0),
Point(3, 2),
Point(2, 3),
Point(0, 0)
])
])
}
}).then(console.log).catch(console.error)
Example 2

Polygon with an outer ring and an inner ring

const { Polygon, LineString, Point } = db.Geo
db.collection('todos').add({
data: {
description: 'eat an apple',
location: Polygon([
// Outer Ring
LineString([ Point(0, 0), Point(30, 20), Point(20, 30), Point(0, 0) ]),
// Inner Ring
LineString([ Point(10, 10), Point(16, 14), Point(14, 16), Point(10, 10) ])
])
}
}).then(console.log).catch(console.error)
Example 3

In addition to constructing a Polygon using the interface, it is possible to use the JSON representation of a Polygon with the equivalent GeoJSON in the following format:

{
"type": "Polygon",
"coordinates": [
[ [lng, lat], [lng, lat], [lng, lat], ..., [lng, lat] ], // Outer Ring
[ [lng, lat], [lng, lat], [lng, lat], ..., [lng, lat] ], // Optional inner ring 1
...
[ [lng, lat], [lng, lat], [lng, lat], ..., [lng, lat] ], // Optional inner ring n
]
}
db.collection('todos').add({
data: {
description: 'eat an apple',
location: {
type: 'Polygon',
coordinates: [
[ [0, 0], [30, 20], [20, 30], [0, 0] ],
[ [10, 10], [16, 14], [14, 16], [10, 10]]
]
}
}
}).then(console.log).catch(console.error)
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
IGeo.Polygon✔️

MultiPoint

Constructs a collection of geolocated "points". A point collection consists of one or more points.

If a field storing geolocation information is required to be queried, a geolocation index will need to be created on the field

Reference

(polygons: JSONMultiPolygon | GeoPolygon[]) => GeoMultiPolygon
ParameterType
polygons`JSONMultiPolygon
Sample Code
Example 1
db.collection('todos').add({
data: {
description: 'eat an apple',
location: db.Geo.MultiPoint([
db.Geo.Point(113, 23),
db.Geo.Point(120, 50),
// ...
])
}
}).then(console.log).catch(console.error)
Example 2

In addition to constructing MultiPoint using the interface, a JSON representation of the point set (MultiPoint) can also be used using the equivalent GeoJSON, in the following format:

{
"type": "MultiPoint",
"coordinates": [
[p1_lng, p1_lat],
[p2_lng, p2_lng]
// ...
]
}
db.collection('todos').add({
data: {
description: 'eat an apple',
location: {
type: 'MultiPoint',
coordinates: [
[113, 23],
[120, 50]
]
}
}
}).then(console.log).catch(console.error)
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
IGeo.MultiPoint✔️

MultiLineString

Constructs a geographic "line" collection. A line collection consists of multiple lines.

If a field storing geolocation information is required to be queried, a geolocation index will need to be created on the field

Reference

(lineStrings: JSONMultiLineString | GeoLineString[]) => GeoMultiLineString
ParameterType
lineStrings`JSONMultiLineString
Sample Code
Example 1
const { LineString, MultiLineString, Point } = db.Geo
db.collection('todos').add({
data: {
description: 'eat an apple',
location: MultiLineString([
LineString([ Point(0, 0), Point(30, 20), Point(20, 30), Point(0, 0) ]),
LineString([ Point(10, 10), Point(16, 14), Point(14, 16), Point(10, 10) ])
])
}
}).then(console.log).catch(console.error)
Example 2

In addition to constructing a MultiLineString using the interface, it is possible to use the equivalent JSON representation of GeoJSON's line collection (MultiLineString) in the following format:

{
"type": "MultiLineString",
"coordinates": [
[ [lng, lat], [lng, lat], [lng, lat], ..., [lng, lat] ],
[ [lng, lat], [lng, lat], [lng, lat], ..., [lng, lat] ],
...
[ [lng, lat], [lng, lat], [lng, lat], ..., [lng, lat] ]
]
}
db.collection('todos').add({
data: {
description: 'eat an apple',
location: {
type: 'MultiLineString',
coordinates: [
[ [0, 0], [3, 3] ],
[ [5, 10], [20, 30] ]
]
}
}
}).then(console.log).catch(console.error)
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
IGeo.MultiLineString✔️

MultiPolygon

Constructs a geographic "polygon" set. A polygon set consists of multiple polygons.

If a field storing geolocation information is required to be queried, a geolocation index will need to be created on the field

Note

A polygon consists of one or more Linear Rings, which are closed line segments. A closed line segment consists of at least four points, the last of which must have the same coordinates as the first, thus indicating the start and end of the ring. If a polygon consists of more than one linear ring, the first linear ring represents the outer ring (the outer boundary) and all subsequent linear rings represent the inner ring (i.e. the hole in the outer ring, not counting the area within this polygon). If a polygon consists of only one linear ring, then this ring is the outer ring.

Polygonal construction rules:

  1. The first linear ring must be the outer ring
  2. The outer ring is not self-paying
  3. All inner rings must be completely within the outer ring
  4. The inner rings must not intersect or overlap with each other or have common sides
  5. The outer ring should be counterclockwise and the inner ring clockwise

Reference

(polygons: JSONMultiPolygon | GeoPolygon[]) => GeoMultiPolygon
ParameterType
polygons`JSONMultiPolygon
Sample Code
Example 1
const { MultiPolygon, Polygon, LineString, Point } = db.Geo
db.collection('todos').add({
data: {
description: 'eat an apple',
location: MultiPolygon([
Polygon([
LineString([ Point(50, 50), Point(60, 80), Point(80, 60), Point(50, 50) ]),
]),
Polygon([
LineString([ Point(0, 0), Point(30, 20), Point(20, 30), Point(0, 0) ]),
LineString([ Point(10, 10), Point(16, 14), Point(14, 16), Point(10, 10) ])
]),
])
}
}).then(console.log).catch(console.error)
Example 2

In addition to constructing a MultiPolygon using the interface, the JSON representation of a MultiPolygon can also be used with the equivalent GeoJSON in the following format:

{
"type": "MultiPolygon",
"coordinates": [
// polygon 1
[
[ [lng, lat], [lng, lat], [lng, lat], ..., [lng, lat] ],
[ [lng, lat], [lng, lat], [lng, lat], ..., [lng, lat] ],
...
[ [lng, lat], [lng, lat], [lng, lat], ..., [lng, lat] ]
],
...
// polygon n
[
[ [lng, lat], [lng, lat], [lng, lat], ..., [lng, lat] ],
[ [lng, lat], [lng, lat], [lng, lat], ..., [lng, lat] ],
...
[ [lng, lat], [lng, lat], [lng, lat], ..., [lng, lat] ]
],
]
}
db.collection('todos').add({
data: {
description: 'eat an apple',
location: {
type: 'MultiPolygon',
coordinates: [
[
[ [50, 50], [60, 80], [80, 60], [50, 50] ]
],
[
[ [0, 0], [30, 20], [20, 30], [0, 0] ],
[ [10, 10], [16, 14], [14, 16], [10, 10]]
]
]
}
}
}).then(console.log).catch(console.error)
API Support
APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
IGeo.MultiPolygon✔️

GeoPoint

Geographical location "Point"

Reference

PropertyTypeDescription
longitudenumberLongitude
latitudenumberLatitude
toJSON

Formatted as a JSON structure

() => object
toString

Formatted as a string

() => string

GeoLineString

The 'line' of geographic position. A line consists of two or more points connected in an orderly fashion.

Reference

PropertyTypeDescription
pointsGeoPoint[]Collection of points
toJSON

Formatted as a JSON structure

() => JSONLineString
toString

Formatted as a string

() => string

GeoPolygon

Geographical location "Polygon"

Reference

PropertyTypeDescription
linesGeoLineString[]Collection of line
toJSON

Formatted as a JSON structure

() => JSONPolygon
toString

Formatted as a string

() => string

GeoMultiPoint

A collection of "points" in a geographic location. A point collection consists of one or more points.

Reference

PropertyTypeDescription
pointsGeoPoint[]Collection of points
toJSON

Formatted as a JSON structure

() => JSONMultiPoint
toString

Formatted as a string

() => string

GeoMultiLineString

Geographical Location "Line" Collection. A line collection consists of multiple lines.

Reference

PropertyTypeDescription
linesGeoLineString[]Collection of line
toJSON

Formatted as a JSON structure

() => JSONMultiLineString
toString

Formatted as a string

() => string

GeoMultiPolygon

Geographical position "polygon" set. A polygon set consists of multiple polygons.

Reference

PropertyTypeDescription
polygonsGeoPolygon[]Collection of points Polygonal
toJSON

Formatted as a JSON structure

() => JSONMultiPolygon
toString

Formatted as a string

() => string

JSONPoint

JSON structure of the geographic "dot"

PropertyTypeDescription
type"Point"Type
coordinates[number, number]Coordinates

JSONLineString

JSON structure of the geographic "line"

PropertyTypeDescription
type"LineString"Type
coordinates[number, number][]Coordinates

JSONPolygon

JSON structure of the geographic "polygon"

PropertyTypeDescription
type"Polygon"Type
coordinates[number, number][][]Coordinates

JSONMultiPoint

JSON structure of a geographic "dot" set.

PropertyTypeDescription
type"MultiPoint"Type
coordinates[number, number][]Coordinates

JSONMultiLineString

JSON structure of a geographic "line" set.

PropertyTypeDescription
type"MultiLineString"Type
coordinates[number, number][][]Coordinates

JSONMultiPolygon

JSON structure of a geographic "polygon" set.

PropertyTypeDescription
type"MultiPolygon"Type
coordinates[number, number][][][]Coordinates

API Support

APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramByteDance Mini-ProgramQQ Mini-ProgramH5React NativeQuick App
IGeo.Point✔️
IGeo.LineString✔️
IGeo.Polygon✔️
IGeo.MultiPoint✔️
IGeo.MultiLineString✔️
IGeo.MultiPolygon✔️