jjzjj

mongodb - 是否可以将展开的数组的一个字段连接到展开的数组上?

coder 2023-11-05 原文

刚接触 mongo,还不知道如何执行查询。

我有一个 accounts 集合,如下所示:

{
    "_id" : ObjectId("1"),
    "time" : ISODate("2018-10-20T05:57:15.372Z"),
    "profileId" : "1",
    "totalUSD" : "1015.5513030613",
    "accounts" : [
        {
            "_id" : ObjectId("2"),
            "accountId" : "1",
            "currency" : "USD",
            "balance" : "530.7934159683763000",
            "available" : "530.7934159683763",
            "hold" : "0.0000000000000000",
            "exchangeRateUSD" : "1"
        },
        {
            "_id" : ObjectId("5"),
            "accountId" : "4",
            "currency" : "BTC",
            "balance" : "0.0759214200000000",
            "available" : "0.07592142",
            "hold" : "0.0000000000000000",
            "exchangeRateUSD" : "6384.995"
        },
    ],
}

我只存储每种货币的 exchangeRateUSD,而不存储 exchangeRateXXX,其中 XXX 是货币名称,因为可以有任意数量的货币和货币对。但是当我查询账户集合时,它总是会被货币对查询,例如:BTC-USD。现在保持简单,我可以假设货币对始终是 XXX-USD。

当我查询帐户集合时,我想为每个帐户对象添加一个“虚拟”字段:exchangeRateCrypto 然后在顶级帐户文档上我想添加 totalCrypto 这只是给定加密中的总账户值(value)。例如:美元账户余额 * exchangeRateCrypto + 加密账户余额 * exchangeRateCrypto(等于 1)。

没有 exchangeRateCryptototalCrypto 的当前查询如下所示:

db.accounts.aggregate([
  { $unwind: '$accounts' },
  { $match: { 'accounts.currency': { $in: [ 'USD', 'BTC' ] }}},
  {
    $group: {
      _id: '$_id',
      time: { $first: '$time' },
      profileId: { $first: '$profileId' },
      accounts:  { $push: '$accounts' },
      totalUSD: { $sum: { $multiply: [ { $toDouble: '$accounts.balance' }, { $toDouble: '$accounts.exchangeRateUSD' } ] } }
    }
  }
]);

我试图弄清楚如何通过简单地执行 1/exchangeRateUSD 然后投影/返回帐户来“到达”BTC 行并计算 exchangeRateCrypto文档和子文档为:

{
    "_id" : ObjectId("1"),
    "time" : ISODate("2018-10-20T05:57:15.372Z"),
    "profileId" : "1",
    "totalUSD" : "1015.5513030613",
    "totalCrypto" : "0.1590527953",   // 530.7934159683763 * 0.0001566171939 + 0.07592142 * 1
    "accounts" : [
        {
            "_id" : ObjectId("2"),
            "accountId" : "1",
            "currency" : "USD",
            "balance" : "530.7934159683763000",
            "available" : "530.7934159683763",
            "hold" : "0.0000000000000000",
            "exchangeRateUSD" : "1",
            "exchangeRateCrypto" : "0.0001566171939",   //  1 / 6384.995
        },
        {
            "_id" : ObjectId("5"),
            "accountId" : "4",
            "currency" : "BTC",
            "balance" : "0.0759214200000000",
            "available" : "0.07592142",
            "hold" : "0.0000000000000000",
            "exchangeRateUSD" : "6384.995",
            "exchangeRateCrypto" : "1"
        },
    ],
}

但还没有找到一个好的方法。

看起来应该很简单,但是还是在学习Mongo。

有什么建议吗?

谢谢!

最佳答案

解决方案可能有点长,可能会缩短,但我希望您逐步理解建议的思维方式。

var secondCurrency = "BTC";
var secondCurrencyFieldName = "exchangeRate" + secondCurrency;
var secondCurrencyFieldNameRef = "$" + secondCurrencyFieldName;
var totalFieldName = "total" + secondCurrency;

db.accounts.aggregate([
    { $unwind: "$accounts" },
    { $match: { "accounts.currency": { $in: [ "USD", secondCurrency ] }}},
    {
        $group: {
            _id: "$_id",
            time: { $first: "$time" },
            profileId: { $first: "$profileId" },
            accounts:  { $push: "$accounts" },
            totalUSD: { $sum: { $multiply: [ { $toDouble: "$accounts.balance" }, { $toDouble: "$accounts.exchangeRateUSD" } ] } }
        }
},
{
    $addFields: {
        [secondCurrencyFieldName]: {
            $filter: {
                input: "$accounts",
                as: "account",
                cond: { $eq: [  "$$account.currency", secondCurrency ] }
            }
        }
    }
},
{
    $addFields: {
        [secondCurrencyFieldName]: {
            $let: {
                vars: { first: { $arrayElemAt: [ secondCurrencyFieldNameRef, 0 ] } },
                in: { $toDouble: "$$first.exchangeRateUSD" }
            }
        }
    }
},
{
    $addFields: {
        accounts: {
            $map: {
                input: "$accounts",
                as: "account",
                in: {
                    $mergeObjects: [
                        "$$account",
                            { 
                            [secondCurrencyFieldName]: {
                                $cond: [ { $eq: [ "$$account.currency", secondCurrency ] }, 1, { $divide: [ 1, secondCurrencyFieldNameRef ] } ]
                                } 
                            }
                    ]
                }
            }
        }
    }
},
{
    $addFields: {
        [totalFieldName]: {
            $reduce: {
                input: "$accounts",
                initialValue: 0,
                in: {
                    $add: [
                        "$$value",
                        { $multiply: [ { $toDouble: "$$this.balance" }, "$$this." + secondCurrencyFieldName ] }
                    ]
                }
            }
        }
    }
}
]).pretty()

所以我们可以从$addFields开始它可以向现有文档添加新字段或替换现有字段。在 $group 阶段之后,您必须找到 USD-XXX 汇率(在下一个管道阶段使用 $filter$let + $arrayElemAt)。有了这个值,您可以再次结合使用 $addFields$map$mergeObjects向嵌套数组添加新字段,该字段将表示 USDXXX 货币之间的比率。然后你可以再次使用 $addFields $reduce获取 XXX 货币的所有账户总数。

输出:

{
    "_id" : ObjectId("5beeec9fef99bb86541abf7f"),
    "time" : ISODate("2018-10-20T05:57:15.372Z"),
    "profileId" : "1",
    "accounts" : [
            {
                    "_id" : ObjectId("5beeec9fef99bb86541abf7d"),
                    "accountId" : "1",
                    "currency" : "USD",
                    "balance" : "530.7934159683763000",
                    "available" : "530.7934159683763",
                    "hold" : "0.0000000000000000",
                    "exchangeRateUSD" : "1",
                    "exchangeRateBTC" : 0.00015661719390539853
            },
            {
                    "_id" : ObjectId("5beeec9fef99bb86541abf7e"),
                    "accountId" : "4",
                    "currency" : "BTC",
                    "balance" : "0.0759214200000000",
                    "available" : "0.07592142",
                    "hold" : "0.0000000000000000",
                    "exchangeRateUSD" : "6384.995",
                    "exchangeRateBTC" : 1
            }
    ],
    "totalUSD" : 1015.5513030612763,
    "exchangeRateBTC" : 6384.995,
    "totalexchangeRateBTC" : 0.15905279535242806
}

关于mongodb - 是否可以将展开的数组的一个字段连接到展开的数组上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53330969/

有关mongodb - 是否可以将展开的数组的一个字段连接到展开的数组上?的更多相关文章

  1. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  2. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  3. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  4. ruby - 多次弹出/移动 ruby​​ 数组 - 2

    我的代码目前看起来像这样numbers=[1,2,3,4,5]defpop_threepop=[]3.times{pop有没有办法在一行中完成pop_three方法中的内容?我基本上想做类似numbers.slice(0,3)的事情,但要删除切片中的数组项。嗯...嗯,我想我刚刚意识到我可以试试slice! 最佳答案 是numbers.pop(3)或者numbers.shift(3)如果你想要另一边。 关于ruby-多次弹出/移动ruby​​数组,我们在StackOverflow上找到一

  5. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  6. ruby - 将数组的内容转换为 int - 2

    我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

  7. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

    我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

  8. ruby-on-rails - 渲染另一个 Controller 的 View - 2

    我想要做的是有2个不同的Controller,client和test_client。客户端Controller已经构建,我想创建一个test_clientController,我可以使用它来玩弄客户端的UI并根据需要进行调整。我主要是想绕过我在客户端中内置的验证及其对加载数据的管理Controller的依赖。所以我希望test_clientController加载示例数据集,然后呈现客户端Controller的索引View,以便我可以调整客户端UI。就是这样。我在test_clients索引方法中试过这个:classTestClientdefindexrender:template=>

  9. ruby - 我可以使用 Ruby 从 CSV 中删除列吗? - 2

    查看Ruby的CSV库的文档,我非常确定这是可能且简单的。我只需要使用Ruby删除CSV文件的前三列,但我没有成功运行它。 最佳答案 csv_table=CSV.read(file_path_in,:headers=>true)csv_table.delete("header_name")csv_table.to_csv#=>ThenewCSVinstringformat检查CSV::Table文档:http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV/Table.html

  10. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

随机推荐