0

I am having following document structure in mongo db

{
"_id": {
    "name": "XYX",
    "rol_no": "1",
    "last_update_dt": "2021-05-10",
    
},
"stud_history": [{
    'std': 'xyz',
    'age': '16'
},
{
    'std': 'mnl',
    'age': '15'
}]
}

and i want to query data like

name:xyz, rol_no:1, last_update_dt: 2021-05-10 and age:16

here i have mentioned only 1 student but i need to query similarly for multiple students.

So my output will be

"_id": {
    "name": "XYX",
    "rol_no": "1",
    "last_update_dt": "2021-05-10",

},
'stud_history': {
    'std': 'xyz',
    'age': '16'
}

Please help

1 Answer 1

1

You have to use the $elemMatch operator inside the projection parameter of the match command to filter output that matches a certain condition.

db.collection.find({  // Find Query
  "_id.name": "XYX",
  "_id.rol_no": "1",
  "_id.last_update_dt": "2021-05-10",
},
{  // Projection Parameter
  "_id": 1,
  "stud_history": {
    "$elemMatch": {  // Filters array elements to those matching the provided condition
      "age": "16"
    }
  }
})

If you want to achieve the same using Aggregation, use the below query:

db.collection.aggregate([
  {
    "$match": {
      "_id.name": "XYX",
      "_id.rol_no": "1",
      "_id.last_update_dt": "2021-05-10",
      
    }
  },
  {
    "$project": {
      "_id": 1,
      "stud_history": {
        $filter: {
          input: "$stud_history",
          as: "item",
          cond: {
            $eq: [ "$$item.age", "16" ]
          }
        }
      }
    }
  },
  {
    // If you want the result to be an object instead of an array
    "$unwind": "$stud_history"
  },
])
Sign up to request clarification or add additional context in comments.

2 Comments

can you post with aggregation?
Add aggregation example to the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.