对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

MongoDB API 参考

Gets a handle for the admin database in a linked MongoDB data source. You can use this to run MongoDB admin commands like admin.getDBNames().

const mongodb = context.services.get("mongodb-atlas");
const admin = mongodb.admin();
admin(): AdminDatabase

The mongodb.admin() method returns an AdminDatabase object. The object contains helper methods that wrap a subset of MongoDB database commands. See admin.getDBNames().

返回 MongoDB 数据源中的数据库名称列表。

const mongodb = context.services.get("mongodb-atlas");
const admin = mongodb.admin();
const dbNames = admin.getDBNames();
getDBNames(): string[]

admin.getDBNames() 方法返回一个字符串数组,其中的每个元素是数据源中的数据库名称。

获取链接的 MongoDB 数据源中的数据库的句柄。

const mongodb = context.services.get("mongodb-atlas");
const db = mongodb.db("myDB");
db(name: string): Database
Parameter
类型
说明

name

字符串

数据库的名称。

mongodb.db() 方法返回一个 Database 对象,可用于访问指定数据库中的集合。

See database.collection().

返回数据库中的集合名称列表。

const mongodb = context.services.get("mongodb-atlas");
const db = mongodb.db("myDB");
const collectionNames = db.getCollectionNames();
getCollectionNames(): string[]

database.getCollectionNames() 方法返回一个字符串数组,其中的每个元素是数据库中的集合名称。

Gets a handle for a collection in a linked MongoDB data source from a database handle.

const mongodb = context.services.get("mongodb-atlas");
const db = mongodb.db("myDB");
const collection = db.collection("myCollection");
collection(name: string): Collection
Parameter
类型
说明

name

字符串

集合的名称。

database.collection() 方法返回一个集合对象,可用于查询指定的集合。

查找集合或视图中与所提供的查询筛选器匹配的所有文档。返回一个游标对象,该对象允许您访问匹配的文档。

const query = { "reviews.0": { "$exists": true } };
const projection = { "_id": 0 };
return itemsCollection.find(query, projection)
.sort({ name: 1 })
.toArray()
.then(items => {
console.log(`Successfully found ${items.length} documents.`)
items.forEach(console.log)
return items
})
.catch(err => console.error(`Failed to find documents: ${err}`))
find(
query?: object,
projection?: object,
options?: object
): Cursor
Parameter
类型
说明

query

object

可选。

A query filter that specifies which documents to find. Specify an empty query ({}) or omit this parameter to match all documents in the collection.

You can use most query selectors except for miscellaneous, geospatial, or bitwise selectors. You may only use these selectors in system functions.

projection

object

可选。

指定 MongoDB 应在匹配文档中包含或省略哪些字段的文档。

要返回匹配文档中的所有字段,请忽略此参数或指定空投影文档 ({})。

要返回特定字段和文档的 _id,请在投影文档中指定这些字段并将值设置为 1:

// Includes the field in returned documents
{ <Field Name>: 1 }

要保留特定字段,请在投影文档中指定值为 0 的字段:

// Withholds the field from returned documents
{ <Field Name>: 0 }

您可以指定要包含的字段或要排除的字段,但不能同时指定这两个字段。 此规则的例外是_id字段,您可以从任何查询中排除该字段。 以下代码显示无效和有效的投影:

// Invalid:
// You can't simultaneously include `name`
// and exclude `address`
{ "name": 1, "address": 0 }
// Valid:
{ "_id": 0, "name": 1 }

options

object

指定其他配置选项的对象。

options.session

ClientSession

可选。

一个会话对象,表示操作发生的事务上下文。要了解详情,请参阅事务。

collection.find() 方法返回一个游标对象,它指向与指定查询匹配的任何文档。您可以使用以下游标方法处理和访问查询结果集中的文档:

方法
说明

cursor.next()

迭代游标并返回一个 Promise,该 Promise 解析为游标中的下一个文档。如果游标耗尽,则该 Promise 将解析为 undefined。

collection.find().next()
.then(doc => console.log("next document", doc))

cursor.toArray()

迭代游标直到耗尽,并返回一个 Promise,它解析为包含所有迭代的文档的数组。

collection.find().toArray()
.then(docs => console.log("all documents", docs))

cursor.skip(amount)

指定要从查询结果集中省略的匹配文档的数量。MongoDB 按排序顺序从结果集中省略文档,直到跳过指定的数字。如果查询还指定了限制,则已跳过的文档不会计入限制阈值。

注意使用cursor.next()或cursor.toArray()检索一个或多个文档后,无法调用此方法。

cursor.limit(limit)

指定在查询结果集中包含的最大文档数。如果结果集包含的文档超过指定的 limit,游标将按顺序返回文档,直到限制为止。

注意使用cursor.next()或cursor.toArray()检索一个或多个文档后,无法调用此方法。

cursor.sort(sort)

Sorts documents in the result set according to the sort filter. Sort documents specify one or more fields to sort on. The value of each field indicates whether MongoDB should sort it in ascending (1) or descending (-1) order. For more information, see cursor.sort.

注意使用cursor.next()或cursor.toArray()检索一个或多个文档后,无法调用此方法。

以下排序文档指定文档应先按 age 从高到低进行排序。在按 age 排序后,结果集应进一步按照 name 字母顺序对每个不同的 age 值进行排序。

{ age: -1, name: 1 }

注意

您无法从函数中返回游标。 相反,请使用cursor.next()或cursor.toArray()评估游标并返回结果。

从集合或视图中查找单个文档。 如果有多个文档与查询匹配,则返回集合中第一个匹配的文档。 findOne()方法不支持排序。 作为一种变通方法,使用find()以及sort()和next()游标方法从已排序的集合中返回单个文档。

collection.find({}).sort({"<Field Name>": 1}).next()
.then(result => console.log("Found Document: ", result))
const query = { "quantity": { "$gte": 25 } };
const projection = {
"title": 1,
"quantity": 1,
}
return itemsCollection.findOne(query, projection)
.then(result => {
if(result) {
console.log(`Successfully found document: ${result}.`);
} else {
console.log("No document matches the provided query.");
}
return result;
})
.catch(err => console.error(`Failed to find document: ${err}`));
findOne(
query?: object,
projection?: object,
options?: object
): Promise<object | null>
Parameter
类型
说明

query

object

可选。

A query filter that specifies which documents to find. Specify an empty query ({}) or omit this parameter to match all documents in the collection.

You can use most query selectors except for miscellaneous, geospatial, or bitwise selectors. You may only use these selectors in system functions.

projection

object

可选。

指定 MongoDB 应在匹配文档中包含或省略哪些字段的文档。

要返回匹配文档中的所有字段,请忽略此参数或指定空投影文档 ({})。

要返回特定字段和文档的 _id,请在投影文档中指定这些字段并将值设置为 1:

// Includes the field in returned documents
{ <Field Name>: 1 }

要保留特定字段,请在投影文档中指定值为 0 的字段:

// Withholds the field from returned documents
{ <Field Name>: 0 }

您可以指定要包含的字段或要排除的字段,但不能同时指定这两个字段。 此规则的例外是_id字段,您可以从任何查询中排除该字段。 以下代码显示无效和有效的投影:

// Invalid:
// You can't simultaneously include `name`
// and exclude `address`
{ "name": 1, "address": 0 }
// Valid:
{ "_id": 0, "name": 1 }

options

object

指定其他配置选项的对象。

options.session

ClientSession

可选。

一个会话对象,表示操作发生的事务上下文。要了解详情,请参阅事务。

collection.findOne() 方法返回一个Promise,该 Promise 解析为集合中与查询匹配的第一个文档。如果没有与指定查询匹配的文档,则该 Promise 解析为 null。

Promise<object | null>

更新集合或视图中的单个文档,并以其更新前或更新后的形式返回文档。

Unlike collection.updateOne(), this action allows you to atomically find, modify, and return a document with the same command. This avoids the risk of other update operations changing the document between separate find and update operations.

// Find the document that describes "lego"
const query = { "name": "lego" };
// Set some fields in that document
const update = {
"$set": {
"name": "blocks",
"price": 20.99,
"category": "toys"
}
};
// Return the updated document instead of the original document
const options = { returnNewDocument: true };
return itemsCollection.findOneAndUpdate(query, update, options)
.then(updatedDocument => {
if(updatedDocument) {
console.log(`Successfully updated document: ${updatedDocument}.`)
} else {
console.log("No document matches the provided query.")
}
return updatedDocument
})
.catch(err => console.error(`Failed to find and update document: ${err}`))
findOneAndUpdate(
query: object,
update: object,
options?: object
): Promise<object | null>
Parameter
类型
说明

query

object

A query filter that specifies which documents to find. Specify an empty query ({}) or omit this parameter to match all documents in the collection.

You can use most query selectors except for miscellaneous, geospatial, or bitwise selectors. You may only use these selectors in system functions.

update

object

一个更新文档,它指定要使用 MongoDB 更新操作符执行的修改。

options

object

指定其他配置选项的对象。

options.upsert

boolean

可选。默认值:false。

一个布尔值,如果为 true,则表示在查询与集合中的任何现有文档都不匹配时,MongoDB 应插入与查询匹配的新文档。

options.sort

boolean

可选。

指定查询排序顺序。您可以指定一个或多个字段以进行排序,其中每个字段的值指示 MongoDB 应按升序 (1) 还是降序 (-1) 进行排序。

以下排序文档指定文档应先按 age 从高到低进行排序。在按 age 排序后,结果集应进一步按照 name 字母顺序对每个不同的 age 值进行排序。

{ age: -1, name: 1 }

options.projection

boolean

指定 MongoDB 应在匹配文档中包含或省略哪些字段的文档。

要返回匹配文档中的所有字段,请忽略此参数或指定空投影文档 ({})。

要返回特定字段和文档的 _id,请在投影文档中指定这些字段并将值设置为 1:

// Includes the field in returned documents
{ <Field Name>: 1 }

要保留特定字段,请在投影文档中指定值为 0 的字段:

// Withholds the field from returned documents
{ <Field Name>: 0 }

您可以指定要包含的字段或要排除的字段,但不能同时指定这两个字段。 此规则的例外是_id字段,您可以从任何查询中排除该字段。 以下代码显示无效和有效的投影:

// Invalid:
// You can't simultaneously include `name`
// and exclude `address`
{ "name": 1, "address": 0 }
// Valid:
{ "_id": 0, "name": 1 }

options.returnNewDocument

boolean

可选。默认值:false。

如果为 true,该方法以更新的形式返回修改的文档,而不是以原始的更新前形式返回文档。

options.session

ClientSession

可选。

一个会话对象,表示操作发生的事务上下文。要了解详情,请参阅事务。

collection.findOneAndUpdate() 方法返回一个Promise,该 Promise 解析为查询覆盖的单个文档。如果没有与指定查询匹配的文档,则该 Promise 解析为 null。

Promise<object | null>

注意

您可以通过设置 options.returnNewDocument 的值,来指定是返回文档的替换前版本还是替换后版本。默认情况下,returnNewDocument 为 false,这表示 Promise 应解析为文档的更新前版本。

覆盖集合或视图中的单个文档,并以替换前或替换后的形式返回该文档。

Unlike collection.updateOne(), this action allows you to atomically find, modify, and return a document with the same command. This avoids the risk of other update operations changing the document between separate find and update operations.

// Find the document that describes "lego"
const query = { "name": "lego" };
// Replace it with a new document
const replacement = {
"name": "blocks",
"price": 20.99,
"category": "toys"
};
// Return the original document as it was before being replaced
const options = { "returnNewDocument": false };
return itemsCollection.findOneAndReplace(query, replacement, options)
.then(replacedDocument => {
if(replacedDocument) {
console.log(`Successfully replaced the following document: ${replacedDocument}.`)
} else {
console.log("No document matches the provided query.")
}
return updatedDocument
})
.catch(err => console.error(`Failed to find and replace document: ${err}`))
findOneAndReplace(
query: object,
replacement: object,
options?: object
): Promise<object | null>
Parameter
类型
说明

query

object

A query filter that specifies which documents to find. Specify an empty query ({}) or omit this parameter to match all documents in the collection.

You can use most query selectors except for miscellaneous, geospatial, or bitwise selectors. You may only use these selectors in system functions.

replacement

object

A document that will replace the matching document. The replacement document cannot contain any MongoDB update operators.

options

object

指定其他配置选项的对象。

options.upsert

boolean

可选。默认值:false。

一个布尔值,如果为 true,则表示在查询与集合中的任何现有文档都不匹配时,MongoDB 应插入与查询匹配的新文档。

options.sort

boolean

可选。

指定查询排序顺序。您可以指定一个或多个字段以进行排序,其中每个字段的值指示 MongoDB 应按升序 (1) 还是降序 (-1) 进行排序。

以下排序文档指定文档应先按 age 从高到低进行排序。在按 age 排序后,结果集应进一步按照 name 字母顺序对每个不同的 age 值进行排序。

{ age: -1, name: 1 }

options.projection

boolean

指定 MongoDB 应在匹配文档中包含或省略哪些字段的文档。

要返回匹配文档中的所有字段,请忽略此参数或指定空投影文档 ({})。

要返回特定字段和文档的 _id,请在投影文档中指定这些字段并将值设置为 1:

// Includes the field in returned documents
{ <Field Name>: 1 }

要保留特定字段,请在投影文档中指定值为 0 的字段:

// Withholds the field from returned documents
{ <Field Name>: 0 }

您可以指定要包含的字段或要排除的字段,但不能同时指定这两个字段。 此规则的例外是_id字段,您可以从任何查询中排除该字段。 以下代码显示无效和有效的投影:

// Invalid:
// You can't simultaneously include `name`
// and exclude `address`
{ "name": 1, "address": 0 }
// Valid:
{ "_id": 0, "name": 1 }

options.returnNewDocument

boolean

可选。默认值:false。

如果为 true,该方法以更新的形式返回修改的文档,而不是以原始的更新前形式返回文档。

options.session

ClientSession

可选。

一个会话对象,表示操作发生的事务上下文。要了解详情,请参阅事务。

collection.findOneAndReplace() 方法返回一个Promise,该 Promise 解析为查询覆盖的单个文档。如果没有与指定查询匹配的文档,则该 Promise 解析为 null。

Promise<object | null>

注意

您可以通过设置 options.returnNewDocument 的值,来指定是返回文档的替换前版本还是替换后版本。默认情况下,returnNewDocument 为 false,这表示 Promise 应解析为文档的更新前版本。

从集合中删除单个文档,并返回已删除文档的原始状态。

Unlike collection.updateOne(), this action allows you to atomically find, modify, and return a document with the same command. This avoids the risk of other update operations changing the document between separate find and update operations.

// Find the first document that has a quantity greater than 25
const query = { "quantity": { "$gte": 25 } };
// Sort the documents in order of descending quantity before
// deleting the first one.
const options = {
"sort": { "quantity": -1 }
}
return itemsCollection.findOneAndDelete(query, options)
.then(deletedDocument => {
if(deletedDocument) {
console.log(`Successfully deleted document that had the form: ${deletedDocument}.`)
} else {
console.log("No document matches the provided query.")
}
return deletedDocument
})
.catch(err => console.error(`Failed to find and delete document: ${err}`))
findOneAndDelete(
query: object,
options?: object
): Promise<object | null>
Parameter
类型
说明

query

object

A query filter that specifies which documents to find. Specify an empty query ({}) or omit this parameter to match all documents in the collection.

You can use most query selectors except for miscellaneous, geospatial, or bitwise selectors. You may only use these selectors in system functions.

options

object

指定其他配置选项的对象。

options.sort

boolean

可选。

指定查询排序顺序。您可以指定一个或多个字段以进行排序,其中每个字段的值指示 MongoDB 应按升序 (1) 还是降序 (-1) 进行排序。

以下排序文档指定文档应先按 age 从高到低进行排序。在按 age 排序后,结果集应进一步按照 name 字母顺序对每个不同的 age 值进行排序。

{ age: -1, name: 1 }

options.projection

boolean

指定 MongoDB 应在匹配文档中包含或省略哪些字段的文档。

要返回匹配文档中的所有字段,请忽略此参数或指定空投影文档 ({})。

要返回特定字段和文档的 _id,请在投影文档中指定这些字段并将值设置为 1:

// Includes the field in returned documents
{ <Field Name>: 1 }

要保留特定字段,请在投影文档中指定值为 0 的字段:

// Withholds the field from returned documents
{ <Field Name>: 0 }

您可以指定要包含的字段或要排除的字段,但不能同时指定这两个字段。 此规则的例外是_id字段,您可以从任何查询中排除该字段。 以下代码显示无效和有效的投影:

// Invalid:
// You can't simultaneously include `name`
// and exclude `address`
{ "name": 1, "address": 0 }
// Valid:
{ "_id": 0, "name": 1 }

options.session

ClientSession

可选。

一个会话对象,表示操作发生的事务上下文。要了解详情,请参阅事务。

collection.findOneAndDelete() 方法返回一个Promise,该 Promise 解析为查询删除的单个文档。如果没有与指定查询匹配的文档,则该 Promise 解析为 null。

Promise<object | null>

将单个文档插入到集合中,并返回插入的文档的 _id。

const newItem = {
"name": "Plastic Bricks",
"quantity": 10,
"category": "toys",
"reviews": [{ "username": "legolover", "comment": "These are awesome!" }]
};
itemsCollection.insertOne(newItem)
.then(result => console.log(`Successfully inserted item with _id: ${result.insertedId}`))
.catch(err => console.error(`Failed to insert item: ${err}`))
insertOne(document: object): Promise<object>
Parameter
类型
说明

document

object

要插入到集合中的文档。

collection.insertOne() 方法返回一个 Promise,它解析为描述插入操作的文档。

Promise<object>
值
类型
说明

result.insertedId

string

插入操作添加到集合中的文档的 _id 值。

将一个或多个文档插入到集合中,并返回一个列表,其中包含每个插入的文档的 _id 值。

const doc1 = { "name": "basketball", "category": "sports", "quantity": 20, "reviews": [] };
const doc2 = { "name": "football", "category": "sports", "quantity": 30, "reviews": [] };
return itemsCollection.insertMany([doc1, doc2])
.then(result => {
console.log(`Successfully inserted ${result.insertedIds.length} items!`);
return result
})
.catch(err => console.error(`Failed to insert documents: ${err}`))
insertMany(
document: object,
options?: { ordered?: boolean },
): Promise<object>
Parameter
类型
说明

documents

object

要插入到集合中的文档的数组。

options

object

指定其他配置选项的对象。

options.ordered

boolean

Optional. A boolean specifying whether the mongod instance should perform an ordered or unordered insert. Defaults to true.

collection.insertMany() 方法返回一个 Promise,它解析为描述插入操作的文档。

Promise<object>
值
类型
说明

result.insertedIds: Array<ObjectID>

string

一个数组,其中包含插入操作添加到集合中的所有文档的 _id 值,按照将文档传递给该方法的顺序排列。

更新集合中的单个文档并返回有关该操作的元数据。

const query = { "name": "football" };
const update = {
"$push": {
"reviews": {
"username": "tombradyfan",
"comment": "I love football!!!"
}
}
};
const options = { "upsert": false };
itemsCollection.updateOne(query, update, options)
.then(result => {
const { matchedCount, modifiedCount } = result;
if(matchedCount && modifiedCount) {
console.log(`Successfully added a new review.`)
}
})
.catch(err => console.error(`Failed to add review: ${err}`))
updateOne(
query: object,
update: object,
options?: object
): Promise<object>
Parameter
类型
说明

query

object

A query filter that specifies which documents to find. Specify an empty query ({}) or omit this parameter to match all documents in the collection.

You can use most query selectors except for miscellaneous, geospatial, or bitwise selectors. You may only use these selectors in system functions.

update

object

一个更新文档,它指定要使用 MongoDB 更新操作符执行的修改。

options

object

指定其他配置选项的对象。

options.upsert

boolean

可选。默认值:false。

一个布尔值,如果为 true,则表示在查询与集合中的任何现有文档都不匹配时,MongoDB 应插入与查询匹配的新文档。

options.session

ClientSession

可选。

一个会话对象,表示操作发生的事务上下文。要了解详情,请参阅事务。

collection.updateOne() 方法返回一个 Promise,该 Promise 会解析为描述更新操作的文档。

Promise<object>
值
类型
说明

result.matchedCount

number

集合中与所提供的查询匹配的文档数。

result.modifiedCount

number

更新操作所修改的文档数量。

result.upsertedId

string

更新或插入操作插入的文档的 _id 值。只有在已启用 upsert 选项并且更新查询与任何文档都不匹配时,才会出现该值。

更新集合中的一个或多个文档,并返回有关该操作的元数据。

const query = {};
const update = { "$mul": { "quantity": 10 } };
const options = { "upsert": false }
return itemsCollection.updateMany(query, update, options)
.then(result => {
const { matchedCount, modifiedCount } = result;
console.log(`Successfully matched ${matchedCount} and modified ${modifiedCount} items.`)
return result
})
.catch(err => console.error(`Failed to update items: ${err}`))
updateMany(
query: object,
update: object,
options?: object
): Promise<object>
Parameter
类型
说明

query

object

A query filter that specifies which documents to find. Specify an empty query ({}) or omit this parameter to match all documents in the collection.

You can use most query selectors except for miscellaneous, geospatial, or bitwise selectors. You may only use these selectors in system functions.

update

object

一个更新文档,它指定要使用 MongoDB 更新操作符执行的修改。

options

object

指定其他配置选项的对象。

options.upsert

boolean

可选。默认值:false。

一个布尔值,如果为 true,则表示在查询与集合中的任何现有文档都不匹配时,MongoDB 应插入与查询匹配的新文档。

options.session

ClientSession

可选。

一个会话对象,表示操作发生的事务上下文。要了解详情,请参阅事务。

collection.updateMany() 方法返回一个 Promise,该 Promise 会解析为描述更新操作的文档。

Promise<object>
值
类型
说明

result.matchedCount

number

集合中与所提供的查询匹配的文档数。

result.modifiedCount

number

更新操作所修改的文档数量。

result.upsertedId

string

更新或插入操作插入的文档的 _id 值。只有在已启用 upsert 选项并且更新查询与任何文档都不匹配时,才会出现该值。

从集合中删除单个文档。

const query = { "name": "lego" };
itemsCollection.deleteOne(query)
.then(result => console.log(`Deleted ${result.deletedCount} item.`))
.catch(err => console.error(`Delete failed with error: ${err}`))
deleteOne(
query: object,
options?: object
): Promise<object>
Parameter
类型
说明

query

object

A query filter that specifies which documents to find. Specify an empty query ({}) or omit this parameter to match all documents in the collection.

You can use most query selectors except for miscellaneous, geospatial, or bitwise selectors. You may only use these selectors in system functions.

options

object

指定其他配置选项的对象。

options.session

ClientSession

可选。

一个会话对象,表示操作发生的事务上下文。要了解详情,请参阅事务。

collection.deleteOne() 方法返回一个 Promise,该 Promise 会解析为描述删除操作的文档。

Promise<object>
值
类型
说明

result.deletedCount

number

集合中通过删除操作删除的文档数。

从集合中删除一个或多个文档。

const query = { "reviews": { "$size": 0 } };
itemsCollection.deleteMany(query)
.then(result => console.log(`Deleted ${result.deletedCount} item(s).`))
.catch(err => console.error(`Delete failed with error: ${err}`))
deleteMany(
query: object,
options?: object
): Promise<object>
Parameter
类型
说明

query

object

A query filter that specifies which documents to find. Specify an empty query ({}) or omit this parameter to match all documents in the collection.

You can use most query selectors except for miscellaneous, geospatial, or bitwise selectors. You may only use these selectors in system functions.

options

object

指定其他配置选项的对象。

options.session

ClientSession

可选。

一个会话对象,表示操作发生的事务上下文。要了解详情,请参阅事务。

collection.deleteMany() 方法返回一个 Promise,该 Promise 会解析为描述删除操作的文档。

Promise<object>
值
类型
说明

result.deletedCount

number

集合中通过删除操作删除的文档数。

执行聚合管道,并返回一个用于访问管道输出文档的游标。

const pipeline = [
{ "$group": {
"_id": "$customerId",
"numPurchases": { "$sum": 1 },
"numItemsPurchased": { "$sum": { "$size": "$items" } }
} },
{ "$addFields": {
"averageNumItemsPurchased": {
"$divide": ["$numItemsPurchased", "$numPurchases"]
}
} }
]
return purchasesCollection.aggregate(pipeline).toArray()
.then(customers => {
console.log(`Successfully grouped purchases for ${customers.length} customers.`)
for(const customer of customers) {
console.log(`customer: ${customer._id}`)
console.log(`num purchases: ${customer.numPurchases}`)
console.log(`total items purchased: ${customer.numItemsPurchased}`)
console.log(`average items per purchase: ${customer.averageNumItemsPurchased}`)
}
return customers
})
.catch(err => console.error(`Failed to group purchases by customer: ${err}`))
aggregate(
pipeline: object[],
options?: object
): Cursor
Parameter
类型
说明

pipeline

object[]

一个或多个聚合管道阶段的大量。 除 $indexStats 之外的所有聚合管道阶段都可用。

options

object

指定其他配置选项的对象。

options.session

ClientSession

可选。

一个会话对象,表示操作发生的事务上下文。要了解详情,请参阅事务。

collection.aggregate() 方法返回一个游标对象,它指向聚合管道的最后阶段输出的任何文档。您可以使用以下方法处理和访问聚合结果集中的文档:

方法
说明

cursor.next()

迭代游标并返回一个 Promise,该 Promise 解析为游标中的下一个文档。如果游标耗尽,则该 Promise 将解析为 undefined。

collection.aggregate(pipeline).next()
.then(doc => console.log("next document", doc))

cursor.toArray()

迭代游标直到耗尽,并返回一个 Promise,它解析为包含所有迭代的文档的数组。

collection.aggregate(pipeline).toArray()
.then(docs => console.log("all documents", docs))

cursor.skip(amount)

指定要从聚合结果集中省略的匹配文档的数量。MongoDB 会按排序顺序从结果集中省略文档,直到跳过指定的数字。

使用cursor.next()或cursor.toArray()检索一个或多个文档后,无法调用此方法。

注意

您无法从函数中返回游标。 相反,请使用cursor.next()或cursor.toArray()评估游标并返回结果。

返回集合或视图中与给定查询匹配的文档的数量。

return itemsCollection.count({ "reviews.0": { "$exists": true } })
.then(numDocs => console.log(`${numDocs} items have a review.`))
.catch(err => console.error("Failed to count documents: ", err))
count(
query?: object,
options?: object
): Promise<number>
Parameter
类型
说明

query

object

可选。

A query filter that specifies which documents to find. Specify an empty query ({}) or omit this parameter to match all documents in the collection.

You can use most query selectors except for miscellaneous, geospatial, or bitwise selectors. You may only use these selectors in system functions.

options

object

指定其他配置选项的对象。

options.session

ClientSession

可选。一个会话对象,表示操作发生的事务上下文。要了解详情,请参阅事务。

collection.count() 方法返回一个 Promise,它解析为集合中与查询匹配的文档的整数个数。

Promise<number>
值
说明
Count Result

numDocs: <integer>

集合中与所提供的查询匹配的文档数。

查找与给定查询筛选器匹配的文档,并返回所有匹配文档中特定字段的不同值的列表。

1const taskCollection = context.services.get("mongodb-atlas")
2 .db("tracker").collection("tasks");
3
4return taskCollection.distinct("status", {})
5 .then(results => {
6 console.log(JSON.stringify(results));
7 console.log(results.length);
8 })
9 .catch(err => console.error(err))
distinct(
field: string,
query: object,
options?: object
): Promise<any[]>
Parameter
类型
说明

field

string

每个文档中要从中查找不同值的字段的名称。

query

object

A query filter that specifies which documents to find. Specify an empty query ({}) or omit this parameter to match all documents in the collection.

You can use most query selectors except for miscellaneous, geospatial, or bitwise selectors. You may only use these selectors in system functions.

options

object

指定其他配置选项的对象。

options.session

ClientSession

可选。

一个会话对象,表示操作发生的事务上下文。要了解详情,请参阅事务。

collection.distinct() 方法会返回 Promise,该 Promise 解析为由不同值组成的数组。

Promise<any[]>

使用单个调用对集合运行多个插入、更新和删除操作。在 bulkWrite() 函数中,您可以指定一个或多个以下写入操作:

  • insertOne

  • updateOne

  • updateMany

  • deleteOne

  • deleteMany

  • replaceOne

注意

只能对单个集合执行批量写入。

exports = async function(arg){
const doc1 = { "name": "velvet elvis", "quantity": 20, "reviews": [] };
const doc2 = { "name": "mock turtleneck", "quantity": 30, "reviews": [] };
var collection = context.services.get("mongodb-atlas")
.db("store")
.collection("purchases");
return await collection.bulkWrite(
[{ insertOne: doc1}, { insertOne: doc2}],
{ordered:true});
};
bulkWrite(
operations: object[],
options?: object
): Promise<null>
Parameter
类型
说明

operations

object[]

要执行的 bulkWrite 操作的数组。支持的操作示例如下:

{ insertOne: { document: { a: 1 } } }
{ updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } }
{ updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } }
{ deleteOne: { filter: {c:1} } }
{ deleteMany: { filter: {c:1} } }
{ replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true}}

options

object

指定其他配置选项的对象。

options.ordered

boolean

可选。默认值:true。

如果为 true,则按指定顺序一次执行一个操作(即串行方式)。如果在处理有序 操作时出现错误,整个批量操作将返回,而不处理列表中的其余操作。

如果为 false,则这些操作是单独执行的,并且可以按并行方式进行处理。如果在处理无序操作时发生错误,则 MongoDB 将继续处理列表中剩余的写入操作。

无序操作在理论上速度更快,因为 MongoDB 可并行执行此类操作,但只应在写入操作不依赖顺序时使用该操作。

options.bypassDocumentValidation

boolean

可选。默认值:false。

如果为 true,该操作将绕过 App Services 中的模式验证。

options.session

ClientSession

可选。

一个会话对象,表示操作发生的事务上下文。要了解详情,请参阅事务。

collection.bulkWrite()函数返回一个解析为 的null Promise。

Promise<null>