I stored the parent document in variable and want to query that variable to find particular subdocuments that satisfy the query in mongoDB
Solution 1:
For fetching users, having client name as "Ahsan"
// shell query
db.getCollection("users").find({"project.clientname": "Ahsan"})
// Mongoose query
await UserModel.find({"project.clientname": "Ahsan"})
For fetching users with matching project details, having client name as "Ahsan"
// shell query
db.getCollection("users").find({"project": {"$elemMatch": {"clientname": "Ahsan"}}}, {"username": 1, "project": {"$elemMatch": {"clientname": "Ahsan"}}})
// Mongoose query
await UserModel.find({"project": {"$elemMatch": {"clientname": "Ahsan"}}}, {"username": 1, "project": {"$elemMatch": {"clientname": "Ahsan"}}})
Solution 2:
For fetching users, having client name as "Ahsan" in denormalized way
// shell query
db.getCollection('users').aggregate([{"$unwind": "$project"}, {"$project": {"_id": "$_id", "username": "$username", "age": "$age", "clientname": "$project.clientname", "payment": "$project.payment", "date": "$project.date"}}])
// Mongoose query
await UserModel.aggregate([{"$unwind": "$project"}, {"$project": {"_id": "$_id", "username": "$username", "age": "$age", "clientname": "$project.clientname", "payment": "$project.payment", "date": "$project.date"}}])