首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >MongoDB:引用集合中所有项的之和

MongoDB:引用集合中所有项的之和
EN

Stack Overflow用户
提问于 2016-02-03 11:23:02
回答 1查看 223关注 0票数 3

我有一些问题得到我所有的帐户余额。所有帐户在收取存款时都提到不同的存款项目。

收款:

代码语言:javascript
运行
复制
[{
    "_id": "56b1ce63315748b44f1174e1",
    "name": "Foo bar",
    "deposits": [
        {
            "$oid": "56b1ce78315748b44f1174e2"
        }
    ]
}]

收取存款:

代码语言:javascript
运行
复制
{
    "_id": {
        "$oid": "56b1deb84f40bfa435e22f3f"
    },
    "account": {
            "$oid": "56b1dea34f40bfa435e22f3e"
    },
    "amount": 300,
    "date": {
        "$date": "2016-02-01T00:00:00.000Z"
    }
}

我试图聚合查询,但它总是返回balance: 0。我想我需要在使用聚合之前填充该项目。但我该怎么做呢?

代码语言:javascript
运行
复制
Accounts.aggregate([
    { $unwind: "$deposits" },
    {
        $group: {
            _id: "$_id",
            name: { "$first": "$name" },
            balance: { $sum: "$deposits.amount" }
        }
    }])

解决方案:

代码语言:javascript
运行
复制
{
    $lookup:
    {
        from: 'deposits',
        localField: 'amount',
        foreignField: 'deposits',
        as: 'deposits'
    },
},
{ $unwind: "$deposits" },
{
    $group: {
        id: "$_id",
        name: { "$first": "$name" },
        balance: { $sum: "$deposits.amount" }
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-02-03 11:46:08

为了加入这两个集合,您需要使用$lookup操作符,您的当前方法不起作用。$lookup操作符只能在MONGO3.2和更高版本中使用。

代码语言:javascript
运行
复制
{
   $lookup:
     {
       from: <collection to join>,
       localField: <field from the input documents>,
       foreignField: <field from the documents of the "from" collection>,
       as: <output array field>
     }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35175685

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档