简体   繁体   中英

Find Sum/Average of values saved with type System.Decimal in mongodb

I want to find min , max , sum and average of some data in my collection. The field, I want to perform these operations on, is stored in the document like this:

在此处输入图片说明

I run the following query

db.getCollection('WorkingFormDataDetail_0d86f13f-e031-4fe6-9308-9c0b03f5dd20').aggregate([
               {
                    "$match" : {
                       "DateDeleted" : null, 
                       "ParentFormKeyID" : NUUID("71b0b572-08c4-4093-8ae2-065a62ca4096"),
                       "FormFieldsData.პაციენტის რეგისტრაციის ადგილი":"ბათუმი" 
                    }
               },
               {
                    "$group" : { 
                        _id:"$FormFieldsData.პაციენტის რეგისტრაციის ადგილი",
                        sum:{$sum: "$FormFieldsData.ფაქტობრივი ხარჯი"},
                        min:{$min: "$FormFieldsData.ფაქტობრივი ხარჯი"},
                        max:{$max: "$FormFieldsData.ფაქტობრივი ხარჯი"},
                        average:{$avg: "$FormFieldsData.ფაქტობრივი ხარჯი"},
                        count:{ $sum: 1}
                    },
               }
               ])

and the response looks like this:

在此处输入图片说明

As you see, sum and avarege values aren't calculated properly. What can be the solution?

This is simplified version of document data:

{
    "_id" : NUUID("fa09b515-42b3-4752-a623-4e472b75be90"),
    "FormID" : NUUID("af4499ea-175r-4ac6-9d42-cb7f04b679d4"),
    "ContractID" : NUUID("db0b685f-13fr-475d-9106-be94e4a4c756"),
    "ParentFormKeyID" : NUUID("cd751b86-833f-4577-9535-456rfde6c1d9"),
    "ParentGridID" : null,
    "ProviderID" : NUUID("bd44a106-bdeb-45r0-837f-653a663b1f7a"),
    "DateCreated" : ISODate("2019-04-17T03:21:20.000Z"),
    "DateChanged" : null,
    "DateDeleted" : null,
    "SubFormsData" : [],
    "FormGridsData" : [] 
    "FormFieldsData" : {
        "ID" : NUUID("fa09b515-42b3-4792-a623-4e522b75be90"),
        "DateCreated" : ISODate("2019-04-17T03:21:20.000Z"),
        "ფაქტობრივი ხარჯი" : {
            "_t" : "System.Decimal",
            "_v" : "0"
        },
        "CommitStatus" : null,
        "ValidationComment" : null
    }
}

Please change your group stage as the below example. I tested your aggregation with my data fields and calculations just work fine.

{_id:null,
                    sum:{$sum: "$FormFieldsData.ფაქტობრივი ხარჯი"},
                    min:{$min: "$FormFieldsData.ფაქტობრივი ხარჯი"},
                    max:{$max: "$FormFieldsData.ფაქტობრივი ხარჯი"},
                    average:{$avg: "$FormFieldsData.ფაქტობრივი ხარჯი"},
                    count:{ $sum: 1}}

even though not really a direct answer, here's my solution to your problem domain using MongoDB.Entities wrapper library. the querying part is no different with the official driver. just use collection.AsQueryable() .

note: BsonType.Decimal128 needs to be used with decimal properties if using official driver. it is not needed for MongoDB.Entities library.

using System;
using System.Linq;
using MongoDB.Entities;
using MongoDB.Driver.Linq;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson;

namespace StackOverflow
{
    public class Form : Entity
    {
        public DateTime? DateDeleted { get; set; }
        public string ParentFormKeyID { get; set; }
        public Data[] FormFieldsData { get; set; }
    }

    public class Data
    {
        public string ID { get; set; }
        public DateTime? DateDeleted { get; set; }
        public string PlaceOfPatientRegistraiton { get; set; }

        [BsonRepresentation(BsonType.Decimal128)]
        public decimal ActualCost { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            new DB("test");

            var form = new Form
            {
                DateDeleted = null,
                ParentFormKeyID = "xxx",
                FormFieldsData = new[] {
                    new Data{ ID="aaa", ActualCost = 10.10m, DateDeleted = null, PlaceOfPatientRegistraiton = "Batumi" },
                    new Data{ ID="bbb", ActualCost = 20.20m, DateDeleted = null, PlaceOfPatientRegistraiton = "Batumi" },
                    new Data{ ID="ccc", ActualCost = 30.30m, DateDeleted = null, PlaceOfPatientRegistraiton = "Batumi" }
                }
            };

            form.Save();

            var res = DB.Collection<Form>()
                        .Where(f => f.DateDeleted == null && f.ParentFormKeyID == "xxx")
                        .SelectMany(d => d.FormFieldsData)
                        .Where(d => d.PlaceOfPatientRegistraiton == "Batumi")
                        .GroupBy(d => d.PlaceOfPatientRegistraiton)
                        .Select(g => new
                        {
                            Place = g.Key,
                            Total = g.Sum(d => d.ActualCost),
                            Minimum = g.Min(d => d.ActualCost),
                            Maximum = g.Max(d => d.ActualCost),
                            Average = g.Average(d => d.ActualCost)
                        }).First();

        }
    }
}

here's the aggregation pipeline it generates:

[{
    "$match": {
        "DateDeleted": null,
        "ParentFormKeyID": "xxx"
    }
}, {
    "$unwind": "$FormFieldsData"
}, {
    "$project": {
        "FormFieldsData": "$FormFieldsData",
        "_id": 0
    }
}, {
    "$match": {
        "FormFieldsData.PlaceOfPatientRegistraiton": "Batumi"
    }
}, {
    "$group": {
        "_id": "$FormFieldsData.PlaceOfPatientRegistraiton",
        "__agg0": {
            "$sum": "$FormFieldsData.ActualCost"
        },
        "__agg1": {
            "$min": "$FormFieldsData.ActualCost"
        },
        "__agg2": {
            "$max": "$FormFieldsData.ActualCost"
        },
        "__agg3": {
            "$avg": "$FormFieldsData.ActualCost"
        }
    }
}, {
    "$project": {
        "Place": "$_id",
        "Total": "$__agg0",
        "Minimum": "$__agg1",
        "Maximum": "$__agg2",
        "Average": "$__agg3",
        "_id": 0
    }
}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM