jjzjj

MongoDB 查询 - 返回切片数组

coder 2023-10-30 原文

我正在尝试针对以下架构指定特定查询:

executionSchema = new Schema(
  timestamp: {type: Number},
  components: [{
    uid: { type: String },
    type: { type: String },
    control_ports: [ { name: String, values: [type: Number] } ]
    input_samples: [ { name: String, values: [type: Number] } ]
    output_samples: [ { name: String, values: [type: Number] } ]
    execution_times: [type: Number]
  }]
)

我想返回一个带有切片数组(input_samples 和 output_samples)的组件,由时间戳指定。这是我到目前为止所做的:

exports.getSamples = (req, res) ->
    timestamp = req.param("timestamp")
    uid = req.param("uid")
    skip = req.param("skip")
    amount = req.param("amount")
    #query = Execution.findOne({'timestamp':timestamp}, 'components.input_samples components.output_samples')
    query = Execution.findOne({'timestamp':timestamp})
    query.where('components.uid').equals(uid)
    query.slice('components.input_samples.values', 5)
    query.slice('components.output_samples.values', 5)
    query.select('components.$.')
    #query.slice('values', 5)
    query.exec ( err, samples )->
        if err
            console.log "Error: "
            console.log err
            res.json err
        else
            console.dir samples
            res.json samples
        return
    return

它实际上返回正确的组件位,它包括数组内的每个元素。不知何故,我设法用另一个查询对数组进行切片,但结果包含每个可用的组件。我想我仍然需要习惯 MongoDb ..

谢谢。

编辑 这是我得到的:

{
    "_id": "5326ca6558f41c510a2659ad",
    "components": [
      {
        "uid": "sine#0",
        "type": "SW",
        "_id": "5326ca6558f41c510a2659b5",
        "execution_times": [
          500,
          450,
          700
        ],
        "output_samples": [
          {
            "name": "Output_Port",
            "_id": "5326ca6558f41c510a2659b6",
            "values": [
              0,
              0.8414709848078965,
              0.9092974268256817,
              0.1411200080598672,
              -0.7568024953079282,
              -0.9589242746631385,
              -0.27941549819892586,
              0.6569865987187891,
              0.9893582466233818,
              0.4121184852417566,
              ...,
              -0.5440211108893698,
              -0.9999902065507035,
              0.5878193939808536,
              0.9983436270438855,
              0.4909953335002932
            ]
          }
        ],
        "input_samples": [],
        "control_ports": [
          {
            "name": "Control 1",
            "_id": "5326ca6558f41c510a2659b7",
                      "values": [
              0,
              0.8414709848078965,
              0.9092974268256817,
              0.1411200080598672,
              -0.7568024953079282,
              -0.9589242746631385,
              -0.27941549819892586,
              0.6569865987187891,
              0.9893582466233818,
              0.4121184852417566,
              ...,
              -0.5440211108893698,
              -0.9999902065507035,
              0.5878193939808536,
              0.9983436270438855,
              0.4909953335002932
            ]
          }
        ]
      }
    ]

以及我想要的(返回这些数组的一个子集):

  {
    "_id": "5326ca6558f41c510a2659ad",
    "components": [
      {
        "uid": "sine#0",
        "type": "SW",
        "_id": "5326ca6558f41c510a2659b5",
        "execution_times": [
          500,
          450,
          700
        ],
        "output_samples": [
          {
            "name": "Output_Port",
            "_id": "5326ca6558f41c510a2659b6",
            "values": [
              0,
              0.8414709848078965,
              0.9092974268256817,
              0.1411200080598672,
              -0.7568024953079282,
              -0.9589242746631385
            ]
          }
        ],
        "input_samples": [],
        "control_ports": [
          {
            "name": "Control 1",
            "_id": "5326ca6558f41c510a2659b7",
                      "values": [
              0,
              0.8414709848078965,
              0.9092974268256817,
              0.1411200080598672,
              -0.7568024953079282
            ]
          }
        ]
      }
    ]

编辑 2:

So this does bring to question, "do you actually mean to have arrays"? Only saying this because as the information is presented, then it seems the only parts that are actually arrays are the "values" fields.

我猜数据比您想象的要复杂一点。组件数组可以保存任意数量的具有唯一“uid”的组件,每个“执行”都可以不同。因此我想我肯定必须为组件使用数组。

The problem with $slice in this context is that you actually don't know "which" array element out of the nesting to operate on. So the style you have presented will not work because the elements could be and any possible index. The correct form, if it were supported, and which it is not would be something like:

数组中特定组件的位置是我唯一不知道的索引,因为数据创建应用程序会在值更新之前初始化执行。因此,我只需要一个“位置 $ 运算符”。它应该看起来像 { "components.$.output_samples.0.values": { "$slice": 5 } }

Nested lists are going to be a problem for various things and are notoriously bad for updating. Where possible you should consider alternatives. In this case if you want to limit your output, then the only practical way is to retrieve the whole document, then process the arrays in code to limit the returned results.

我想这是一个小错误,简化了我的真实意图。我想使用切片运算符跳过前 n 个元素并检索以下 m 个元素。这两个变量应由用户指定。但是,output_samples.0.values 字段可能包含数百万个值。甚至更多。这就是为什么我想收集用户需要的尽可能多的值。

非常感谢您详细的回答。

最佳答案

关于 $slice 的问题这里或任何类型的数组投影都是您在定义的架构中嵌套数组的事实。我还注意到 positional $ 的使用运算符(operator)偷偷溜进去看一眼,所以最好在文档的上下文中从那里进行解释。

所以在那个页面上有这个:

  • The $ projection operator limits the content of the field to the first element that matches the query document.
  • The field must appear in the query document

因此对于初学者来说,您并不是在查询中要求匹配任何数组的任何元素中的特定字段。仅凭这一点,就无法对匹配元素进行投影。在任何情况下,只有第一个匹配的数组元素可能被匹配,即使您这样做也是如此。

在您的结构中,您唯一可以匹配的是数组“components”中的顶部位置。就在顶部。

$slice 的问题在这种情况下,您实际上不知道“哪个” 嵌套之外的数组元素要对其进行操作。因此,您所呈现的样式将不起作用,因为元素可能是任何可能的索引。正确的形式,如果它支持,而它应该是这样的:

{ "components.0.output_samples.0.values": { "$slice": 5 } }

因为您需要指定指向您实际谈论的元素的索引路径。

所以这确实让人产生疑问,“你真的意味着拥有数组”吗?之所以这么说,是因为在呈现信息时,似乎只有 “值” 字段才是真正的数组部分。

嵌套列表将成为各种问题,并且众所周知不利于更新。在可能的情况下,您应该考虑替代方案。在这种情况下,如果您想限制输出,那么唯一可行的方法是检索整个文档,然后在代码中处理数组以限制返回的结果。

考虑到所有“其他”数组嵌套有一个

即使是下面的“非常复杂”的咒语也只会(“有点”)以它现在的形式起作用em>一个元素。所以它使这成为可能但不切实际:

db.components.aggregate([
   { "$unwind": "$components" },
   { "$unwind": "$components.output_samples"},
   { "$unwind": "$components.control_ports"},
   { "$unwind": "$components.output_samples.values"},
   { "$limit": 5 },
   { "$group": { 
       "_id": { 
           "_id": "$_id", 
           "components": {
               "uid": "$components.uid",
               "type": "$components.type",
               "_id": "$components._id",
               "execution_times": "$components.execution_times",
               "output_samples": {
                   "name": "$components.output_samples.name",
                   "_id": "$components.output_samples._id"
               },
               "input_samples": "$components.input_samples",
               "control_ports": "$components.control_ports"
           }
       }, 
       "output_samples_values": {"$push": "$components.output_samples.values" }
   }},
   { "$project": { 
       "_id": { 
           "_id": "$_id._id", 
           "components": {
               "uid": "$_id.components.uid",
               "type": "$_id.components.type",
               "_id": "$_id.components._id",
               "execution_times": "$_id.components.execution_times",
               "output_samples": {
                   "name": "$_id.components.output_samples.name",
                   "_id": "$_id.components.output_samples._id",
                   "values": "$output_samples_values"
               },
               "input_samples": "$_id.components.input_samples",
               "control_ports": {
                   "name": "$_id.components.control_ports.name",
                   "_id": "$_id.components.control_ports._id"
               }
           }
       }, 
       "control_ports_values": "$_id.components.control_ports.values"
   }},
   { "$unwind": "$control_ports_values" },
   { "$limit": 5 },
   { "$group": { 
       "_id": { 
           "_id": "$_id._id", 
           "components": {
               "uid": "$_id.components.uid",
               "type": "$_id.components.type",
               "_id": "$_id.components._id",
               "execution_times": "$_id.components.execution_times",
               "output_samples": {
                   "name": "$_id.components.output_samples.name",
                   "_id": "$_id.components.output_samples._id",
                   "values": "$_id.components.output_samples.values"
               },
               "input_samples": "$_id.components.input_samples",
               "control_ports": {
                   "name": "$_id.components.control_ports.name",
                   "_id": "$_id.components.control_ports._id"
               }
           }
       }, 
       "control_ports_values": {"$push": "$control_ports_values" }
   }}
])

所有这些只是按前 5 个值对两个数组进行切片。

因此,如果您需要嵌套数组,则在检索结果时在代码中进行“切片”。否则将架构更改为更实际地适合您的目的的内容。

关于MongoDB 查询 - 返回切片数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22453513/

有关MongoDB 查询 - 返回切片数组的更多相关文章

  1. ruby - ECONNRESET (Whois::ConnectionError) - 尝试在 Ruby 中查询 Whois 时出错 - 2

    我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.

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

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

  3. 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上找到一

  4. 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]

  5. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

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

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

  7. ruby - 检查数组是否在增加 - 2

    这个问题在这里已经有了答案:Checktoseeifanarrayisalreadysorted?(8个答案)关闭9年前。我只是想知道是否有办法检查数组是否在增加?这是我的解决方案,但我正在寻找更漂亮的方法:n=-1@arr.flatten.each{|e|returnfalseife

  8. ruby - 如果指定键的值在数组中相同,如何合并哈希 - 2

    我有一个这样的哈希数组:[{:foo=>2,:date=>Sat,01Sep2014},{:foo2=>2,:date=>Sat,02Sep2014},{:foo3=>3,:date=>Sat,01Sep2014},{:foo4=>4,:date=>Sat,03Sep2014},{:foo5=>5,:date=>Sat,02Sep2014}]如果:date相同,我想合并哈希值。我对上面数组的期望是:[{:foo=>2,:foo3=>3,:date=>Sat,01Sep2014},{:foo2=>2,:foo5=>5:date=>Sat,02Sep2014},{:foo4=>4,:dat

  9. ruby - 在 Ruby 中用键盘诅咒数组浏览 - 2

    我正在尝试在Ruby中制作一个cli应用程序,它接受一个给定的数组,然后将其显示为一个列表,我可以使用箭头键浏览它。我觉得我已经在Ruby中看到一个库已经这样做了,但我记不起它的名字了。我正在尝试对soundcloud2000中的代码进行逆向工程做类似的事情,但他的代码与SoundcloudAPI的使用紧密耦合。我知道cursesgem,我正在考虑更抽象的东西。广告有没有人见过可以做到这一点的库或一些概念证明的Ruby代码可以做到这一点? 最佳答案 我不知道这是否是您正在寻找的,但也许您可以使用我的想法。由于我没有关于您要完成的工作

  10. ruby-on-rails - 在 Rails 和 ActiveRecord 中查询时忽略某些字段 - 2

    我知道我可以指定某些字段来使用pluck查询数据库。ids=Item.where('due_at但是我想知道,是否有一种方法可以指定我想避免从数据库查询的某些字段。某种反拔?posts=Post.where(published:true).do_not_lookup(:enormous_field) 最佳答案 Model#attribute_names应该返回列/属性数组。您可以排除其中一些并传递给pluck或select方法。像这样:posts=Post.where(published:true).select(Post.attr

随机推荐