AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。
Docs Menu

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()メソッドは string の配列を返します。各要素はデータソース内のデータベースの名前です。

リンクされた MongoDB データ ソース内のデータベースのハンドルを取得します。

const mongodb = context.services.get("mongodb-atlas");
const db = mongodb.db("myDB");
db(name: string): Database
Parameter
タイプ
説明

name

string

データベースの名前。

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

string

コレクションの名前。

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 は 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()を使用して 1 つ以上のドキュメントを取得した後、このメソッドを呼び出すことはできません。

cursor.limit(limit)

クエリ結果セットに含めるドキュメントの最大数を指定します。 結果セットに指定されたlimitを超えるドキュメントが含まれている場合、カーソルは制限までドキュメントを順番に返します。

注cursor.next()またはcursor.toArray()を使用して 1 つ以上のドキュメントを取得した後、このメソッドを呼び出すことはできません。

cursor.sort(sort)

sortフィルターに従って結果セット内のドキュメントを並べ替えます。 ソートドキュメントは、ソートする 1 つ以上のフィールドを指定します。 各フィールドの値は、MongoDB が昇順( 1 )または降順( -1 )のどちらでソートするかを示します。 詳細については、「 cursor.sort 」を参照してください。

注cursor.next()またはcursor.toArray()を使用して 1 つ以上のドキュメントを取得した後、このメソッドを呼び出すことはできません。

次の並べ替えドキュメントでは、ドキュメントを最高から最低へのageで最初にソートすることを指定しています。 月別で並べ替えると、結果セットはさらに、個別の経過時間ごとにアルファベット順にnameで並べ替える必要があります。

{ age: -1, name: 1 }

注意

関数からカーソルを返すことはできません。 代わりに、 cursor.next()またはcursor.toArray()を使用してカーソルを評価し、結果を返します。

コレクションまたはビューから 1 つのドキュメントを検索します。 複数のドキュメントがクエリに一致する場合、コレクション内の最初に一致するドキュメントが返されます。 findOne()メソッドは並べ替えをサポートしていません。 回避策として、 sort()およびnext()カーソル メソッドとともにfind()を使用して、ソートされたコレクションから単一のドキュメントを返します。

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 は null に解決されます。

Promise<object | null>

コレクションまたはビュー内の 1 つのドキュメントを更新し、更新前または更新後の形式でドキュメントを返します。

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

options

object

追加の構成オプションを指定するオブジェクト。

options.upsert

boolean

任意。デフォルト: false 。

ブール値がtrueの場合、クエリがコレクション内の既存のドキュメントと一致しない場合に、MongoDB はクエリに一致する新しいドキュメントを挿入する必要があることを示します。

options.sort

boolean

任意。

クエリのソート順序を指定します。 並べ替えるフィールドを 1 つ以上指定できます。各フィールドの値は、MongoDB が昇順( 1 )または降順( -1 )のどちらでソートするかを示します。

次の並べ替えドキュメントでは、ドキュメントを最高から最低へのageで最初にソートすることを指定しています。 月別で並べ替えると、結果セットはさらに、個別の経過時間ごとにアルファベット順にnameで並べ替える必要があります。

{ 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 は null に解決されます。

Promise<object | null>

注意

ドキュメントの置換前バージョンまたは置換後のバージョンのどちらを返すか指定するには、 options.returnNewDocumentの値を設定します。 デフォルトでは、 returnNewDocumentはfalseであり、Promise は更新前のバージョンのドキュメントに解決される必要があることを示しています。

コレクションまたはビュー内の 1 つのドキュメントを上書きし、置換前または置換後の形式でドキュメントを返します。

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

一致するドキュメントを置き換えるドキュメント。 置き換えドキュメントには MongoDB更新演算子 を含めることはできません。

options

object

追加の構成オプションを指定するオブジェクト。

options.upsert

boolean

任意。デフォルト: false 。

ブール値がtrueの場合、クエリがコレクション内の既存のドキュメントと一致しない場合に、MongoDB はクエリに一致する新しいドキュメントを挿入する必要があることを示します。

options.sort

boolean

任意。

クエリのソート順序を指定します。 並べ替えるフィールドを 1 つ以上指定できます。各フィールドの値は、MongoDB が昇順( 1 )または降順( -1 )のどちらでソートするかを示します。

次の並べ替えドキュメントでは、ドキュメントを最高から最低へのageで最初にソートすることを指定しています。 月別で並べ替えると、結果セットはさらに、個別の経過時間ごとにアルファベット順にnameで並べ替える必要があります。

{ 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 は null に解決されます。

Promise<object | null>

注意

ドキュメントの置換前バージョンまたは置換後のバージョンのどちらを返すか指定するには、 options.returnNewDocumentの値を設定します。 デフォルトでは、 returnNewDocumentはfalseであり、Promise は更新前のバージョンのドキュメントに解決される必要があることを示しています。

コレクションから 1 つのドキュメントを削除し、削除されたドキュメントを、削除される直前として返します。

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

任意。

クエリのソート順序を指定します。 並べ替えるフィールドを 1 つ以上指定できます。各フィールドの値は、MongoDB が昇順( 1 )または降順( -1 )のどちらでソートするかを示します。

次の並べ替えドキュメントでは、ドキュメントを最高から最低へのageで最初にソートすることを指定しています。 月別で並べ替えると、結果セットはさらに、個別の経過時間ごとにアルファベット順にnameで並べ替える必要があります。

{ 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 は null に解決されます。

Promise<object | null>

コレクションに 1 つのドキュメントを挿入し、挿入されたドキュメントの_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値。

コレクションに 1 つ以上のドキュメントを挿入し、挿入された各ドキュメントの_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値を、メソッドに渡された順序で含む配列。

コレクション内の 1 つのドキュメントを更新し、操作に関するメタデータを返します。

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

options

object

追加の構成オプションを指定するオブジェクト。

options.upsert

boolean

任意。デフォルト: false 。

ブール値がtrueの場合、クエリがコレクション内の既存のドキュメントと一致しない場合に、MongoDB はクエリに一致する新しいドキュメントを挿入する必要があることを示します。

options.session

ClientSession

任意。

操作が発生するトランザクションコンテキストを表すセッション オブジェクト。 詳細については、「トランザクション 」を参照してください。

collection.updateOne()メソッドは、 更新操作を記述するドキュメントに解決される Promise を返します。

Promise<object>
値
タイプ
説明

result.matchedCount

number

指定されたクエリに一致するコレクション内のドキュメントの数。

result.modifiedCount

number

更新操作によって変更されたコレクション内のドキュメントの数。

result.upsertedId

string

アップサート 操作によって挿入されたドキュメントの_id値。 この値は、 upsertオプションが有効になっていて、更新クエリがどのドキュメントにも一致しない場合にのみ存在します。

コレクション内の 1 つ以上のドキュメントを更新し、操作に関するメタデータを返します。

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

options

object

追加の構成オプションを指定するオブジェクト。

options.upsert

boolean

任意。デフォルト: false 。

ブール値がtrueの場合、クエリがコレクション内の既存のドキュメントと一致しない場合に、MongoDB はクエリに一致する新しいドキュメントを挿入する必要があることを示します。

options.session

ClientSession

任意。

操作が発生するトランザクションコンテキストを表すセッション オブジェクト。 詳細については、「トランザクション 」を参照してください。

collection.updateMany()メソッドは、 更新操作を記述するドキュメントに解決される Promise を返します。

Promise<object>
値
タイプ
説明

result.matchedCount

number

指定されたクエリに一致するコレクション内のドキュメントの数。

result.modifiedCount

number

更新操作によって変更されたコレクション内のドキュメントの数。

result.upsertedId

string

アップサート 操作によって挿入されたドキュメントの_id値。 この値は、 upsertオプションが有効になっていて、更新クエリがどのドキュメントにも一致しない場合にのみ存在します。

コレクションから 1 つのドキュメントを削除します。

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<object>
値
タイプ
説明

result.deletedCount

number

削除操作によって削除されたコレクション内のドキュメントの数。

コレクションから 1 つ以上のドキュメントを削除します。

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<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[]

1 つ以上の集計パイプラインステージの配列。 $indexStats を除くすべての集計パイプラインステージが利用できます。

options

object

追加の構成オプションを指定するオブジェクト。

options.session

ClientSession

任意。

操作が発生するトランザクションコンテキストを表すセッション オブジェクト。 詳細については、「トランザクション 」を参照してください。

collection.aggregate()メソッドは、集計パイプラインの最終ステージからのドキュメント出力を指すカーソル オブジェクトを返します。 次の方法を使用して、集計結果セット内のドキュメントを操作し、アクセスできます。

方式
説明

cursor.next()

カーソルを反復処理し、カーソル内の次のドキュメントに解決される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()を使用して 1 つ以上のドキュメントを取得した後、このメソッドを呼び出すことはできません。

注意

関数からカーソルを返すことはできません。 代わりに、 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<any[]>

コレクションに対して複数の挿入、アップデート、削除操作を 1 回の呼び出しで実行します。 bulkWrite()関数内で、次の書き込み操作を 1 つ以上指定できます。

  • insertOne

  • updateOne

  • updateMany

  • deleteOne

  • deleteMany

  • replaceOne

注意

一括書込みは 1 つのコレクションに対してのみ操作できます。

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の場合、操作は指定された順序で一度に 1 つずつ実行されます(つまり、 シリアルに)する必要があります。 順序付き操作の処理中にエラーが発生した場合、リスト内の残りの操作を処理せずに一括操作全体が返されます。

falseの場合、操作は独立して実行され、並列処理される可能性があります。 順序なし操作の処理中にエラーが発生した場合、MongoDB はリスト内の残りの書込み操作の処理を続行します。

順序なし操作は MongoDB が並列に実行できるため論理的に高速ですが、書込みが順序に依存しない場合にのみ使用してください。

options.bypassDocumentValidation

boolean

任意。デフォルト: false 。

trueの場合、操作は Atlas App Services のスキーマ検証をバイパスします。

options.session

ClientSession

任意。

操作が発生するトランザクションコンテキストを表すセッション オブジェクト。 詳細については、「トランザクション 」を参照してください。

collection.bulkWrite()関数は、 に解決される Promisenull を返します。

Promise<null>