算上MongoDB中的子文档领域,总金额 [英] count the subdocument field and total amount in mongodb

查看:288
本文介绍了算上MongoDB中的子文档领域,总金额的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个集合下方的文件:

  {
    _id:的ObjectId(54acfb67a81bf9509246ed81),
    Billno:1234,
    详细信息:
        {
            项code:12,
            ITEMNAME:Paste100g
            数量:2,
            价格:50
        },
        {
            项code:14,
            ITEMNAME:Paste30g
            数量:4,
            价格:70
        },
        {
            项code:12,
            ITEMNAME:Paste100g
            数量:4,
            价格:100
        }
    ]
}{
    _id:的ObjectId(54acff86a81bf9509246ed82),
    Billno:1237,
    详细信息:
        {
            项code:12,
            ITEMNAME:Paste100g
            数量:3,
            价格:75
        },
        {
            项code:19,
            ITEMNAME:dates100g
            数量:4,
            价格:170
        },
        {
            项code:22,
            ITEMNAME:dates200g
            数量:2,
            价格:160
        }
    ]
}

我需要显示以下输出。请帮助

所需的输出:

  -------------------------------------- -------------------------------------------
项目code ITEMNAME totalprice totalqty
-------------------------------------------------- -------------------------------
12 Paste100g 225 9
14 Paste30g 70 4
19 dates100g 170 4
22 dates200g 160 2


解决方案

MongoDB的聚合管道可为您解决问题。你得到了详细的数组我处理与 $放松 ,然后使用的 $组 为求和的总数:

db.collection.aggregate([
    //放松数组脱正常化作为文件
    {$开卷:$详细信息},    //组你想要的密钥,并提供其他值
    {$组:{
        _id:$ details.item code,
        ITEMNAME:{$第一:$ details.itemname},
        totalprice:{$总和:$ details.price},
        totalqty:{$总和:$ details.qty}
    }}
])

在理想情况下,你想有一个 $匹配 在那里阶段先过滤掉任何不相关的数据。这基本上是MongoDB的查询,并采取一切相同的参数和运算符。

这里大部分其实很简单。该 $放松 是有点像SQL中的加入不同的是在嵌入式结构中的加入已经作出,所以你只是去正常化就像参加一个之间会做许多表关系,但只是在文档内部。它基本上重复的父文档部件到数组为每个阵列成员作为一个新的文档。

然后 $组 一键的作品,如GROUP BY,其中的重头戏是 _id 值。一切有独特的和所有其它值由分组运算符。

云集

这是操作的地方如 $第一个 进来。由于手册页所述,这需要从钥匙前面提到的分组边界的第一的价值。你要这个,因为这个领域的所有值都是可能是一样的,所以这是一个合乎逻辑的选择,只是挑了第一的比赛。

最后是 $总和 分组运算符,它做什么应该可以预期的。下的钥匙的添加或总结所有提供的值加在一起总共提供。就像SQL SUM()

另外请注意,所有的 $ prefixed名存在与当前文档中的字段/属性变量名的聚合框架如何处理正在处理中。 点符号用于引用嵌入领域/属性嵌套在一个父属性名之内。

学习聚集在MongoDB中是非常有用的。这是一般的查询是什么东西超出了基本的SELECT语句是SQL。不只是为分组但对于其他的操作为好。

通读所有聚集经营的文档,也看看一个 SQL聚集映射的文档,如果你的一般指南有一些熟悉SQL开始。这有助于解释概念,并展示了一些事情可以做的。

I've a collection with below documents:

{
    "_id" : ObjectId("54acfb67a81bf9509246ed81"),
    "Billno" : 1234,
    "details" : [ 
        {
            "itemcode" : 12,
            "itemname" : "Paste100g",
            "qty" : 2,
            "price" : 50
        }, 
        {
            "itemcode" : 14,
            "itemname" : "Paste30g",
            "qty" : 4,
            "price" : 70
        }, 
        {
            "itemcode" : 12,
            "itemname" : "Paste100g",
            "qty" : 4,
            "price" : 100
        }
    ]
}

{
    "_id" : ObjectId("54acff86a81bf9509246ed82"),
    "Billno" : 1237,
    "details" : [ 
        {
            "itemcode" : 12,
            "itemname" : "Paste100g",
            "qty" : 3,
            "price" : 75
        }, 
        {
            "itemcode" : 19,
            "itemname" : "dates100g",
            "qty" : 4,
            "price" : 170
        }, 
        {
            "itemcode" : 22,
            "itemname" : "dates200g",
            "qty" : 2,
            "price" : 160
        }
    ]
}

I need to display below output. Please help

Required Output:

---------------------------------------------------------------------------------
itemcode           itemname               totalprice       totalqty
---------------------------------------------------------------------------------  
12                 Paste100g               225                9
14                 Paste30g                 70                4
19                 dates100g               170                4
22                 dates200g               160                2

解决方案

The MongoDB aggregation pipeline is available to solve your problem. You get details out of an array my processing with $unwind and then using $group to "sum" the totals:

db.collection.aggregate([
    // Unwind the array to de-normalize as documents
    { "$unwind": "$details" },

    // Group on the key you want and provide other values
    { "$group": { 
        "_id": "$details.itemcode",
        "itemname": { "$first": "$details.itemname" },
        "totalprice": { "$sum": "$details.price" },
        "totalqty": { "$sum": "$details.qty" }
    }}
])

Ideally you want a $match stage in there to filter out any irrelevant data first. This is basically MongoDB query and takes all the same arguments and operators.

Most here is simple really. The $unwind is sort of like a "JOIN" in SQL except that in an embedded structure the "join" is already made, so you are just "de-normalizing" like a join would do between "one to many" table relationships but just within the document itself. It basically "repeats" the "parent" document parts to the array for each array member as a new document.

Then the $group works of a key, as in "GROUP BY", where the "key" is the _id value. Everything there is "distinct" and all other values are gathered by "grouping operators".

This is where operations like $first come in. As described on the manual page, this takes the "first" value from the "grouping boundary" mentioned in the "key" earlier. You want this because all values of this field are "likely" to be the same, so this is a logical choice to just pick the "first" match.

Finally there is the $sum grouping operator which does what should be expected. All supplied values under the "key" are "added" or "summed" together to provide a total. Just like SQL SUM().

Also note that all the $ prefixed names there is how the aggregation framework deals with variables for "field/property" names within the current document being processed. "Dot notation" is used to reference the embedded "fields/properties" nested within a parent property name.

It is useful to learn aggregation in MongoDB. It is to general queries what anything beyond a basic "SELECT" statement is to SQL. Not just for "grouping" but for other manipulation as well.

Read through the documentation of all aggregation operators and also take a look a SQL to Aggregation Mapping in the documentation as a general guide if you have some familiarity with SQL to begin with. It helps explain concepts and shows some things that can be done.

这篇关于算上MongoDB中的子文档领域,总金额的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆