0

please help me this case.

I have a document:

Example:

{
  "id":1,
  "rules": [
    {
      "trigger": {
        "criteria": [
          {
            "type": "A"
          }
        ]
      },
      "benefit": "iphone"
    },
    {
      "trigger": {
        "criteria": [
          {
            "type": "A"
          }
        ]
      },
      "benefit": "ipad"
    },
    {
      "trigger": {
        "criteria": [
          {
            "type": "B"
          }
        ]
      },
      "benefit": "ipad"
    }
  ]
}

My expected result is to get benefit iphone and ipad from this document.

[
  {
    "benefit": "iphone"
  },
  {
    "benefit": "ipad"
  }
]

So I have tried this query:

db.collection.find({"id":"1"},{"rules":{"$elemMatch":{"trigger.criteria.type":"A"}}}})

I know that $elementMatch just return first match, so changed to aggregate refer to this LINK

db.collection.aggregate([
    {$match: {'id': '1'}},
    {$project: {
        rules: {$filter: {
            input: '$rules',
            as: 'rule',
            cond: {$eq: ['$$rule.trigger.criteria.type', 'A']}
        }},
        _id: 0
    }}
])

I just receive this.

{ "_id" : ObjectId("1"), "rules" : [ ] }

Please correct me for this query. Thanks a lot

Park Jay
  • 249
  • 6
  • 14

1 Answers1

0

You can use $unwind pipeline followed by $match.finally use $project to project the desired field only.

db.collection.aggregate([
    {$match: {'_id': '1'}},
   {
       $unwind: "$rules"
   },
    {
       $unwind: "$rules.trigger.criteria"
   },
   {
       $match: {"rules.trigger.criteria.type":"A"}
   },
   {
       $project: 
       {
          "benefit": "$rules.benefit",
           _id:0
       }
   }

])
Nishant Bhardwaz
  • 924
  • 8
  • 21