1

I've a typical data stored in bit weird way (may not make much sense but its historical data stored as such):

{
   1:{"text:text"},
   2:{"text:text"},
   3:{"text:text"},
   4:{"text:text"},
   5:{"text:text"}
}

Here, keys are simple numbers ranging from 0-100000. Now i want to fetch by dynamic key data like, fetch records with key ranging 2-4, something like this:

{
   2:{"text:text"},
   3:{"text:text"},
   4:{"text:text"},
}

Any suggestions handling this kind of data with dynamic keys?

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Prasad.CH
  • 492
  • 1
  • 5
  • 25

1 Answers1

1

For a given range, say 2-4, you can create an object with properties which are in dot notation to represent the embedded dynamic keys in the query. Constructing the object itself would use the bracket notation:

var i = start = 2,
    end = 4,        
    search = "text",
    query = {};

for (;i<=end;i++){ query[i+".text"] = search; }
db.collection.find(query);

Check the demo below.

var i = start = 2,
    end = 4,     
 search = "text",
 query = {};

for (;i<=end;i++){ query[i+".text"] = search; }

pre.innerHTML = "query: " + JSON.stringify(query, null, 4);
<pre id="pre"></pre>
chridam
  • 100,957
  • 23
  • 236
  • 235
  • i suppose this code is javascript but not mongodb query or map-reduce function? what am i suppose to do with this piece of code. – Prasad.CH Nov 20 '15 at 08:45
  • @Prasad.CH You can use the JavaScript in mongo shell since it is an interactive JavaScript interface to MongoDB – chridam Nov 20 '15 at 08:51