0

I'm trying to retrieve all of my charts data with a query on date attribute but it returns all of charts data and not good results.

Model

charts: [
        {
            date: {
                type: Date,
                required: true,
            },
        },
    ],

My query

Model.findById({ _id: '5f47f7d65ff89941ecbc8340', 'charts.date': { $gte: '2020-01-15' } })

I want to retrieve all charts elements whose date is greater than '2020-01-15'.

b-user
  • 97
  • 1
  • 3
  • 10
  • Can you add what it returns? – Pritthish Nath Aug 27 '20 at 20:55
  • is your field 'Date' of type ISODate or string in mongoDb? Check this post: https://stackoverflow.com/questions/8848314/isodate-is-not-defined – raga Aug 27 '20 at 22:19
  • [{ open: 48.22, close: 50.47, high: 49.77, low: 49, volume: 51353, date: 2007-06-05T00:00:00.000Z }, ... 3451 more items ] – b-user Aug 28 '20 at 06:46
  • My query working with a no array field but with charts which is an array of objects, it not working! I don't understand why? – b-user Aug 28 '20 at 06:57

1 Answers1

0

The find function and its related friends operate on documents. The query you've submitted will match on any document with the matching _id and a charts.date in the specified range, and return the entire document.

If you can get by with just the first matching element from the chart array, you could use $elemMatch in a projection.

If you need to get all matching elements, you'll need to use aggregation with a $filter.

Joe
  • 25,000
  • 3
  • 22
  • 44
  • I tried this but I have no results ... Model.aggregate([ { $match: { symbol: 'CW8' } }, { $unwind: '$charts' }, { $match: { 'charts.date': { $gte: '2020-01-12' } } }, { $group: { _id: '$_id', charts: { $push: '$charts.date' } } } ]) – b-user Aug 28 '20 at 10:21
  • Are the dates actually stored as strings? – Joe Aug 28 '20 at 10:22
  • Dates are stored as ISODate: 2020-01-12T00:00:00.000+00:00 – b-user Aug 28 '20 at 10:59
  • The you'll need to use an ISODate with `$gte` in order to match. – Joe Aug 28 '20 at 11:27
  • I tried { $gte: new Date('2020-01-12').toISOString() }, it's not working either – b-user Aug 28 '20 at 12:07
  • `toISOString()` returns string, not `ISODate` – Joe Aug 28 '20 at 16:05