0

I'm trying to find documents within my collection that have a numeric value greater than x amount. The documentation explains how to do this for top level values however I'm struggling to retrieve the correct data for values that are within child objects.

Sample JSON

{ "_id" : ObjectId("5c32646c9f3315c3e8300673"), "key" : "20190107", "__v" : 0, "chart" : [ { "_id" : ObjectId("5c3372e5c35e924984f28e03"), "volume" : "0", "close" : "47.24", "time" : "09:30 AM" }, { "_id" : ObjectId("5c3372e5c35e924984f28d34"), "volume" : "50", "close" : "44.24", "time" : "09:50 AM" } ] }

I want to retrieve volumes greater than 10. I've tried

db.symbols.find({"chart.volume": { $gt: 10 } } )

db.symbols.find({"volume": { $gt: 10 } } )

Any help appreciated.

Stephanie Parker
  • 371
  • 3
  • 17

1 Answers1

0

Your sample JSON has string values for the chart.volume field. If it was numeric, then your first solution:

db.symbols.find({"chart.volume": { $gt: 10 } } )

would work fine. The docs do explain how to do this.

Andrew Nessin
  • 1,206
  • 2
  • 15
  • 22
  • Ahhh of course! Thank you. I don't suppose there is a way I can easily recursively change all of the values to numbers without having to rescrape/import them? – Stephanie Parker Jan 07 '19 at 16:31
  • There is. You can do this `db.symbols.find().forEach( function (e) { e.chart = e.chart.map(c => { c.volume = parseInt(c.volume); return c; }); db.symbols.save(e); } )`. Refer to these answers: [this](https://stackoverflow.com/a/3792958/5800527) and [this](https://stackoverflow.com/a/41853085/5800527) – Andrew Nessin Jan 08 '19 at 16:31