/ Pivot Table / Connecting To Data Source / MongoDB
Search results

MongoDB in JavaScript Pivot Table control

23 Mar 2023 / 4 minutes to read

This section describes how to consume data from MongoDB database using MongoDB Driver and MongoDB Bson libraries and bind it to the Pivot Table via a Web API controller.

Steps to connect the MongoDB database via Web API application

1. Download the ASP.NET Core Web Application from this GitHub repository.

2. The application named as PivotController (server-side) that is downloaded from the above GitHub repository includes the PivotController.cs file under Controllers folder, which is helps to do data communication with Pivot Table.

3. In the Web API controller (aka, PivotController), MongoClient helps to connect the MongoDB database. Next, using the GetDatabase and GetCollection methods, you can retrieve data from the database. The Find method of the IMongoDatabase is used to populate the retrieved data into a List, as shown in the following code snippet.

Copied to clipboard
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using MongoDB.Driver;
using MongoDB.Bson;

namespace PivotController.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class PivotController : ControllerBase
    {
        private static List<ProductDetails> FetchMongoDbResult()
        {
            // Replace with your own connection string.
            string connectionString = "<Enter your valid connection string here>";
            MongoClient client = new MongoClient(connectionString);
            IMongoDatabase database = client.GetDatabase("sample_training");
            var collection = database.GetCollection<ProductDetails>("ProductDetails");
            return collection.Find(new BsonDocument()).ToList();
        }
        public class ProductDetails
        {
            public ObjectId Id { get; set; }
            public int Sold { get; set; }
            public double Amount { get; set; }
            public string? Country { get; set; }
            public string? Products { get; set; }
            public string? Year { get; set; }
            public string? Quarter { get; set; }
        }
    }
}

4. In the Get() method of the PivotController.cs file, the FetchMongoDbResult() method is used to retrieve the MongoDB data as a List, which is then serialized into JSON using JsonConvert.SerializeObject().

Copied to clipboard
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using MongoDB.Bson;
using MongoDB.Driver;

namespace PivotController.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class PivotController : ControllerBase
    {
        [HttpGet(Name = "GetMongoDbResult")]
        public object Get()
        {
            return JsonConvert.SerializeObject(FetchMongoDbResult());
        }

        private static List<ProductDetails> FetchMongoDbResult()
        {
            // Replace with your own connection string.
            string connectionString = "<Enter your valid connection string here>";
            MongoClient client = new MongoClient(connectionString);
            IMongoDatabase database = client.GetDatabase("sample_training");
            var collection = database.GetCollection<ProductDetails>("ProductDetails");
            return collection.Find(new BsonDocument()).ToList();
        }
        public class ProductDetails
        {
            public ObjectId Id { get; set; }
            public int Sold { get; set; }
            public double Amount { get; set; }
            public string? Country { get; set; }
            public string? Products { get; set; }
            public string? Year { get; set; }
            public string? Quarter { get; set; }
        }
    }
}

5. Run the web application (aka, PivotController) and it will be hosted within the URL https://localhost:44346.

6. Finally, the retrieved data from MongoDB database which is in the form of JSON can be found in the Web API controller available in the URL link https://localhost:44346/pivot, as shown in the browser page below.

Hosted Web API URL

Connecting the Pivot Table to the hosted Web API URL

1. Download the Typescript Pivot Table sample from this GitHub repository.

2. Next, map the hosted Web API’s URL link https://localhost:44346/pivot to the Pivot Table component in app.ts by using the url property under dataSourceSettings.

Copied to clipboard
import { PivotView, FieldList } from '@syncfusion/ej2-pivotview';

PivotView.Inject(FieldList);
let pivotObj: PivotView = new PivotView({
    dataSourceSettings: {
        url: 'https://localhost:44346/pivot',
        //Other codes here...
    }
});
pivotObj.appendTo('#PivotView');

3. Frame and set the report based on the data retrieved from the MongoDB database.

Copied to clipboard
import { PivotView, FieldList } from '@syncfusion/ej2-pivotview';

PivotView.Inject(FieldList);
let pivotObj: PivotView = new PivotView({
    dataSourceSettings: {
        url: 'https://localhost:44346/pivot',
        enableSorting: true,
        columns: [
            { name: 'Year' }
        ],
        values: [
            { name: 'Sold', caption: "Units Sold"},
            { name: 'Amount', caption: "Sold Amount"}
        ],
        rows: [
            { name: 'Country' },
            { name: 'Products' }
        ]
    },
    showFieldList: true,
    width: '100%',
    height: 350,
});
pivotObj.appendTo('#PivotView');

Run the sample to get the following result.

PivotTable bound with MongoDB database