简体   繁体   中英

Write a complex Mongo query in Rails ORM

I want to convert mongo query to rails ORM query for the below json.

Rails query is:

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
        ]
      },

    }
  }
])

Please look at this as well:

https://mongoplayground.net/p/fb9IMkC1fCs

Collection is the corresponding class and this is what I've tried so far,

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 does not provide a DSL for constructing aggregation pipelines. The driver provides a basic helper to perform aggregation pipeline queries, but returns raw data as BSON::Document instances.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM