1

I am building Node-Js application using Mongoose my question is: Is there a way to return the matched Objects from document instead of the entire object to be more specific I want to return the company_report that contains a date < at 2018-06-10 here is my the example with my code:

[
  {
    companyName: "example",
    "history": [
      {
        "company_report_result": [
          {
            "attribut": 1111,

          }
        ],
        "date": ISODate("2018-06-06T08:11:00.000Z")
      },
      {
        "company_report_result": [
          {
            "attribut": 22222,

          }
        ],
        "date": ISODate("2018-06-12T08:11:00.000Z")
      },
      {
        "company_report_result": [
          {
            "attribut": 3333,

          }
        ],
        "date": ISODate("2018-06-07T08:11:00.000Z")
      }
    ]
  }
]

query:

Campaign.find({ 'table.history.date': { $gt: new Date('2018-06-10') } })
Ashh
  • 36,647
  • 11
  • 71
  • 96
devv
  • 37
  • 1
  • 6

1 Answers1

0

You need to use $filter aggregation operator which gives only the matched element from the array and escapes the other elements

db.collection.aggregate([
  {
    $match: {
      "history.date": {
        $gte: new Date('2018-06-10')
      }
    }
  },
  {
    $project: {
      companyName: 1,
      history: {
        $filter: {
          input: "$history",
          as: "hist",
          cond: {
            $gte: [
              "$$hist.date",
              new Date('2018-06-10')
            ]
          }
        }
      }
    }
  }
])

Above query will return

[
  {
    companyName: "example",
    "history": [
      {
        "company_report_result": [
          {
            "attribut": 22222,

          }
        ],
        "date": ISODate("2018-06-12T08:11:00.000Z")
      }
    ]
  }
]
Ashh
  • 36,647
  • 11
  • 71
  • 96