Sunday, 12 March 2017

mongoose 4.7.5: how to fetch subdocuments in array

Am trying to fetch and filter subdocuments in array.

The document has this structure:

{
    "_id": {
        "$oid": "58bc4fa0fd85f439ee3ce716"
    },
    "updatedAt": {
        "$date": "2017-03-08T20:39:19.390Z"
    },
    "createdAt": {
        "$date": "2017-03-05T17:49:20.455Z"
    },
    "app": {
        "$oid": "58ae10852035431d5a746cbd"
    },
    "stats": [
        {
            "meta": {
                "key": "value",
                "key": "value"
            },
            "_id": {
                "$oid": "58bc4fc4fd85f439ee3ce718"
            },
            "data": "data",
            "updatedAt": {
                "$date": "2017-03-05T17:49:56.305Z"
            },
            "createdAt": {
                "$date": "2017-03-05T17:49:56.305Z"
            }
        },
        {
            "meta": {
                "key": "value",
                "key": "value"
            },
            "_id": {
                "$oid": "58c06bf79eaf1f15aafe39d0"
            },
            "data": "data",
            "updatedAt": {
                "$date": "2017-03-08T20:39:19.391Z"
            },
            "createdAt": {
                "$date": "2017-03-08T20:39:19.391Z"
            }
        }
    ]
}

What i want to get is the subdocuments in the stats array between two dates I tried mongoose queries chain:

Model.findById(id)
  .select('stats')
  .where('stats.createdAt').gt(data-value).lt(data-value)

But the result always the full document including the all the subdocuments.

Also I tried aggregation like this:

  Model.aggregate({ 
    $match: { 
      'stats.createdAt': '2017-03-05T17:49:56.305Z' 
    } 
  })

The result is always null



via user3462064

No comments:

Post a Comment