Home > OS >  I stored the parent document in variable and want to query that variable to find particular subdocum
I stored the parent document in variable and want to query that variable to find particular subdocum

Time:01-23

I stored user in "user" variable using this query

const user = await UserModel.findById({_id : req.userID});

This user has array of projects.

for example:

user = {
username : 'Alex',
age : 40,
project : [
{
clientname : "Faateh",
payment : 500,
date : 2021 , 21 , 01
},
{
clientname : "Ahsan",
payment : 700,
date : 2021 , 21 , 01
},

]
}

I want to get only those projects with clientname == "Ahsan" using query on this "user" variable. How do i do it? Please help

CodePudding user response:

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"}}})

CodePudding user response:

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"}}])
  •  Tags:  
  • Related