【问题标题】:Write a complex Mongo query in Rails ORM在 Rails ORM 中编写复杂的 Mongo 查询
【发布时间】:2019-11-27 09:19:32
【问题描述】:

我想将 mongo 查询转换为以下 json 的 rails ORM 查询。

Rails 查询是:

db.collection.aggregate([
  {
    $match: {
      "data.toc.ge.ge._id": "5b"
    }
  },
  {
    $unwind: "$data.toc.ge"
  },
  {
    $unwind: "$data.toc.ge.ge"
  },
  {
    $group: {
      _id: null,
      book: {
        $push: "$data.toc.ge.ge._value"
      }
    }
  },
  {
    $project: {
      _id: 0,
      first: {
        $arrayElemAt: [
          "$book",
          0
        ]
      },

    }
  }
])

请也看看这个:

https://mongoplayground.net/p/fb9IMkC1fCs

Collection 是对应的类,这是我迄今为止尝试过的,

unwind2=  {'$unwind': "$data.toc.ge.ge"}
unwind3=  {'$unwind': "$data.toc.ge.ge.ge"}
group= {'$group': {_id: nil, book: {'$push': "$data.toc.ge.ge.ge._display_name"}}}
match= {'$match': {"data.toc.ge.ge.ge._id": "m121099"}}
project= {'$project': {_id: 0, 'mytopic': {'$arrayElemAt': ["$book",0]},}}

answer = collection.aggregate([match,unwind1,unwind2,unwind3,group,project]).to_a

【问题讨论】:

  • 我想你正在使用 Mongoid。 Mongoid 不为 MongoDB 聚合框架提供 ORM。聚合允许在没有特定方案的情况下构造任意对象。

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


【解决方案1】:

Mongoid 不提供用于构建聚合管道的 DSL。该驱动程序提供了一个基本的帮助程序来执行聚合管道查询,但将原始数据作为 BSON::Document 实例返回。

https://docs.mongodb.com/ruby-driver/current/tutorials/ruby-driver-aggregation/

【讨论】:

    猜你喜欢
    • 2019-08-13
    • 2020-01-03
    • 1970-01-01
    • 1970-01-01
    • 2013-06-09
    • 1970-01-01
    • 1970-01-01
    • 2021-05-27
    • 2015-12-06
    相关资源
    最近更新 更多