0

I have these questions documents in mongodb, and it can have multiple answers documents embedded in it. I am using mongoid in rails app.

{
  "_id" : ObjectId("5642993541021327d3000004"),
  "asked_to" : [ 
      "5642978841021327d3000000", 
      "564297f441021327d3000001"
  ], 
  "text": "What is your hobby?",
  "answers": [
    {
      "_id" : ObjectId("56429baf41021327d3000005"),
      "user_id": "5642978841021327d3000000",
      "type": "text",
      "text": "Playing soccer",
      "status": "active"
    },
    {
      "_id" : ObjectId("46429baf41021327d3000092"),
      "user_id": "564297f441021327d3000001",
      "type": "video",
      "video_url": "http://www.myvideo.com/ewkrjwert7",
      "status": "inactive"
    }
  ]
}


{
  "_id" : ObjectId("7642993541021327d30000022"),
  "asked_to" : [ 
      "9642978841021327d3000027", 
      "564297f441021327d3000001",
      "994297f441021327d3000002"
  ], 
  "text": "What is your name?",
  "answers": [
    {
      "_id" : ObjectId("26429baf41021327d3000004"),
      "user_id": "564297f441021327d3000001",
      "type": "text",
      "text": "John abc",
      "status": "inactive"
    },
    {
      "_id" : ObjectId("86429baf41021327d3000091"),
      "user_id": "9642978841021327d3000027",
      "type": "text",
      "text": "Mary Kay",
      "status": "inactive"
    },
    {
      "_id" : ObjectId("86429baf41021327d3000091"),
      "user_id": "994297f441021327d3000002",
      "type": "video",
      "video_url": "http://www.myvideo.com/khgfdiuweo",
      "status": "active"
    }
  ]
}

{
  "_id" : ObjectId("5642993541021327d3000004"),
  "asked_to" : [ 
      "5642978841021327d3000000", 
      "564297f441021327d3000001"
  ], 
  "text": "Where do you live?",
  "answers": [
    {
      "_id" : ObjectId("56429baf41021327d3000005"),
      "user_id": "5642978841021327d3000000",
      "type": "video",
      "text": "Playing soccer",
      "status": "active"
    },
    {
      "_id" : ObjectId("46429baf41021327d3000092"),
      "user_id": "564297f441021327d3000001",
      "type": "video",
      "video_url": "http://www.myvideo.com/ewkrjwert7",
      "status": "inactive"
    }
  ]
}

I want to get all those questions documents where asked_to includes 564297f441021327d3000001 and any of the embedded answer documents match this criteria user_id ==564297f441021327d3000001 type == text || status == active

So in above example, using my conditions, it should return me all above three question documents, as every question, there is one embedded document that matches these conditions

I tried writing query in mongoid like this, but of course it wont work as there is no or like this I can use.:

questions.where(asked_to: '564297f441021327d3000001').and("answer.user_id": "564297f441021327d3000001").and("answer.status": "active" or "answer.type": "text" )

So how can I achieve what I am looking for?

JVK
  • 3,782
  • 8
  • 43
  • 67

0 Answers0