简体   繁体   English

在mongodb中查找用System.Decimal类型保存的值的总和/平均值

[英]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. 我想找到集合中某些数据的minmaxsumaverage 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. 如您所见,sum和avarege值计算不正确。 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. 即使不是真正的直接答案,这也是我使用MongoDB.Entities包装器库解决问题域的方法。 the querying part is no different with the official driver. 查询部分与官方驱动程序没有什么不同。 just use collection.AsQueryable() . 只需使用collection.AsQueryable()

note: BsonType.Decimal128 needs to be used with decimal properties if using official driver. 注意:如果使用官方驱动程序,则BsonType.Decimal128需要与十进制属性一起使用。 it is not needed for MongoDB.Entities library. MongoDB.Entities库不需要它。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 System.Decimal是否一致? - Is System.Decimal consistent? 初始化System.Decimal v初始化十进制数据类型 - Initialising a System.Decimal v Initialisting a decimal data type 如何解决强制转换为值类型&#39;System.Decimal&#39;的错误 - How to solve the cast to value type 'System.Decimal' failure error 无法将类型为&#39;System.Collections.Generic.List`1 [System.Decimal]&#39;的对象强制转换为&#39;System.IConvertible&#39; - Unable to cast object of type 'System.Collections.Generic.List`1[System.Decimal]' to type 'System.IConvertible' SSIS:无法将类型为“ System.Decimal”的对象转换为类型为“ System.Char []” - SSIS: Unable to cast object of type 'System.Decimal' to type 'System.Char[]' 如何解决:无法将类型为“ System.Decimal”的对象转换为类型为“ System.String”的对象 - How To Solve :Unable to cast object of type 'System.Decimal' to type 'System.String' 无法将对象类型System.Decimal转换为排序列表框中的System.String - Unable to cast object type System.Decimal to type System.String from sorting listbox DataGridView:“System.DBNull”类型的 Object 无法转换为“System.Decimal”类型 - DataGridView: Object of type 'System.DBNull' cannot be converted to type 'System.Decimal' 无法将“System.Decimal”类型的对象转换为“System.String”类型。 创建编辑视图后 - Unable to cast object of type 'System.Decimal' to type 'System.String'. after creating the EDIT View 无法将类型为“ System.Decimal”的对象转换为类型为“ System.String”的对象 - Unable to cast object of type 'System.Decimal' to type 'System.String'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM