WebJobs/Azure Functions trigger providing reading and writing MongoDB documents directly from your functions
You can install the package using the standard dotnet CLI:
dotnet add package Kevsoft.Azure.WebJobs.Extensions.MongoDB
or by using the package manager within Visual Studio:
PM> Install-Package Kevsoft.Azure.WebJobs.Extensions.MongoDB
The package supports lots of binding types, For a full list see the example project within this repository.
We support binding to the MongoClient
, IMongoDatabase
and IMongoCollection<>
:
[FunctionName("NativeObjects")]
public static async Task<IActionResult> RunNativeObjects(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "native")] HttpRequest req,
[MongoDb(ConnectionStringSetting = "MongoDbUrl")]
MongoClient client,
[MongoDb("test", ConnectionStringSetting = "MongoDbUrl")]
IMongoDatabase database,
[MongoDb("test", "test", ConnectionStringSetting = "MongoDbUrl")]
IMongoCollection<BsonDocument> collection)
{
// Do something with `client`, `database` or `collection`.
return new OkObjectResult();
}
We can also bind directly to a document within your database:
[FunctionName("QueryIdByObjectId")]
public static IActionResult RunByObjectId(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "{database}/{collection}/{id}")] HttpRequest req,
[MongoDb("{database}", "{collection}", "{id}", ConnectionStringSetting = "MongoDbUrl")]
BsonDocument document)
{
var value = document.ToJson();
return new OkObjectResult(value);
}
If we're not using an ObjectId
as our _id
we can set the type on the binding:
[MongoDb("{database}", "{collection}", "{id}", ConnectionStringSetting = "MongoDbUrl", IdType = typeof(int))]
Adding documents is done by binding to an IAsyncCollector<>
:
[FunctionName("InsertFunction")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "{database}/{collection}")] HttpRequest req,
[MongoDb("{database}", "{collection}", ConnectionStringSetting = "MongoDbUrl")] IAsyncCollector<BsonDocument> documents)
{
var json = await req.ReadAsStringAsync().ConfigureAwait(false);
var document = BsonDocument.Parse(json);
await documents.AddAsync(document)
.ConfigureAwait(false);
return new AcceptedResult();
}
- Fork
- Hack!
- Pull Request