mercredi 27 novembre 2019

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

Aucun commentaire:

Enregistrer un commentaire