0

In my offers collection I have documents like this:

{
"_id" : ObjectId("535419d2d6ad229f217359af"),
"application" : "app1",
"category_id" : "nord outdoor",
"category_name" : "nord outdoor",
"id" : "810928",
"name" : "offer name",
"ref_code" : "810928",
"srcs" : {
    "src1" : {
        "price" : 149.9,
        "updated_at" : ISODate("2014-04-20T19:21:15Z"),
        "url" : "http://www.offer.com/810928?src=1"
    },
    "src2" : {
        "price" : 149.9,
        "updated_at" : ISODate("2014-04-20T20:21:15Z"),
        "url" : "http://www.offer.com/810928?src=2"
    }
},
"updated_at" : ISODate("2014-04-20T19:21:15Z")
}

I need to run the following query (using Ruby Moped):

app = 'app1'
tolerance = Time.now - 3600
srcs = %w(src1 src2 srcN)
result = []
srcs.each do |src|
    query = collection.find({:application => app, :"srcs.#{src}.updated_at" => {:$lt => tolerance}})
    query = query.sort(:"srcs.#{src}.updated_at" => 1)
    result << query.limit(512).entries
end

How do I create index to perform this query, keeping in mind that srcs can assume any value?

  • 2
    With the data model above you would need a separate index for each src type. You may be better off making "srcs" an array of sources which you could then create a multi-key index for (http://docs.mongodb.org/manual/core/index-multikey/) – James Wahlin Apr 21 '14 at 17:27
  • Thanks for comment @JamesWahlin, but I have this model limitation. I need to guarantee an efficient upsert in this collection, with only one src type per document, which is not possible using an array of sources. – Arthur Bailão Apr 21 '14 at 18:15
  • I'd concur with @JamesWahlin - you can't do an index the way you want without creating an index for every combination (which would not be recommended). Your data model isn't structured efficiently for an index with MongoDB. Have you looked at the array support/update options? – WiredPrairie Apr 21 '14 at 19:00

0 Answers0