Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

find only specific inner array where condition match, ignroe other | MongoDB | Node Js

In mongoose I am trying to fetch the inner record which match with specific condition. but it always return me both records, like it only treat the parent node rather than child.

$project aggregate function doesn’t seems working as I expected
`

[{
  "_id": {
    "$oid": "636b9958d6ea5d0cc85d20a6"
  },
  "project_type": 1,
  "title": "Pariatur Aut repreh",
  "id": 4,
  "drawings": [
    {
      "id": 1,
      "assigned_to": 4,
      "assigned_name": "Desirae Sandoval",
      "assigned_by": 3
    },
    {
      "id": 1,
      "assigned_to": 6,
      "assigned_name": "Desirae Sandoval",
      "assigned_by": 3
    }
  ],
  "status": 1,
  "created_at": {
    "$date": {
      "$numberLong": "1667995992724"
    }
  }
}]

`

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am expecting to get only that drawing which is assigned_to : 6
I have tried aggregate, match, project everything but none of them working, it always fetch both of the drawing, but I am expecting to fetch only one drawing 
This what I am expecting

    [{
  "_id": {
    "$oid": "636b9958d6ea5d0cc85d20a6"
  },
  "project_type": 1,
  "title": "Pariatur Aut repreh",
  "id": 4,
  "drawings": [
    {
      "id": 1,
      "assigned_to": 6,
      "assigned_name": "Desirae Sandoval",
      "assigned_by": 3
    }
  ],
  "status": 1,
  "created_at": {
    "$date": {
      "$numberLong": "1667995992724"
    }
  }
}]

>Solution :

Use a filter

db.collection.aggregate([
  {
    $match: {
      "drawings.assigned_to": 6
    }
  },
  {
    $project: {
      project_type: 1,
      title: 1,
      id: 1,
      status: 1,
      created_at: 1,
      drawings: {
        $filter: {
          input: "$drawings",
          as: "drawings",
          cond: {
            $eq: [
              "$$drawings.assigned_to",
              6
            ]
          }
        }
      }
    }
  },
  
])

Edit: Add a match to remove all documents without any documents with any drawings.assigned_to of 6

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading