【问题标题】:Ruby Mongo Driver Projection ElemmatchRuby Mongo 驱动程序投影 Elemmatch
【发布时间】:2016-10-09 01:53:12
【问题描述】:

按照http://www.w3resource.com/mongodb/mongodb-elemmatch-projection-operators.php 中的代码,我使用 ruby​​ mongodb 驱动程序设置了一个测试数据库。

对于那些在家跟随的人,您首先需要按照https://docs.mongodb.com/ecosystem/tutorial/ruby-driver-tutorial/#creating-a-client 的描述安装mongo驱动程序,然后运行以下命令。

client = Mongo::Client.new([ '127.0.0.1:27017'], :database => 'mydb')

test = client['test']

文档 = { "_id" => 1, “批次”=>10452, “tran_details”=>[ { “数量” => 200, “普拉特” => 50, “mrp” => 70 }, { “数量” => 250, “普拉特” => 50, “mrp” => 60 }, { “数量” => 190, “普拉特” => 55, “mrp” => 75 } ] }

test.insert_one(doc)

插入在 w3 教程中创建的所有不同文档。

如果你看一下 w3 教程中的示例 2,翻译后的 ruby​​ find 是:

test.find({"batch" => 10452}).projection({"tran_details" => {"$elemMatch" => {"prate" => 50, "mrp" => {"$gte" => 70}}}}).to_a

返回与示例中相同的结果。

=> [{"_id"=>1, "tran_details"=>[{"qty"=>200, "prate"=>50, "mrp"=>70}]}, {"_id"= >3}, {"_id"=>4}]

我的问题是我想用上述约束(mrp gte 70 等)约束结果,同时还指定返回哪些字段。

例如,仅约束具有 mrp gte 70 的 tran_details,但在返回的结果中仅包含 prate 字段(或字段的任何子集)。

我只能返回带有查询的 prate 字段:

test.find({"batch" => 10452}).projection({"tran_details.prate" => 1}).to_a

我想将两种不同投影的效果结合起来,但我还没有看到任何关于如何在线进行的文档。如果将两个投影串在一起,则只有最终的投影有效果。

【问题讨论】:

    标签: ruby-on-rails ruby mongodb mongodb-query mongodb-ruby


    【解决方案1】:

    给外面的任何人--

    在投影上使用 $elemMatch 最多可以解决一个元素。但是,$elemMatch 只返回找到的第一个结果。要仅返回符合特定条件的多层嵌入文档的部分,您需要使用聚合框架。

    test.find({
      'tran_details.prate' => { '$gt' => 56 }
    }).projection({
      tran_details: {
        '$elemMatch' => {
          prate: { '$gt' => 56 }
        }
      },
      'tran_details.qty' => 1,
      'tran_details.mrp' => 1,
      batch: 1,
      _id: 0
    }).to_a
    

    要仅返回符合特定条件的多层嵌入文档的部分,您需要使用聚合框架。

    这里是示例代码

    test.aggregate([{
       '$match': {
          '$or': [
              {'batch': 10452}, {'batch': 73292}]}}, 
       {'$project':
          {trans_details: 
              {'$filter': {
                 input: '$tran_details', 
                 as: 'item', 
                 cond: {'$and':[
                   {'$gte' => ['$$item.prate', 51]},
                   {'gt' =>    ['$$item.prate', 53]}
                 ]}
               }
          }
       }
    }]).to_a
    

    如果有人看到这个并且知道如何从字符串中动态地构造 ruby​​ 查询,请告诉我!与 bson 有关,但仍在尝试查找相关文档。谢谢 -

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-24
      • 1970-01-01
      • 2015-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多