Reputation: 451
I am using mongoDB and new to native command, I like to use alias name for the field name
here I am using two tables (Company and employee), In company table employee fields are associated with many to one association
My actual JSON is as follows. Table one and its name is "company"
comp_name : "YYYY",
employers : [
{
name : "Mike",
status : "Active",
id : 01
},{
name : "San",
status: "InActive",
id : 02
}
],
status : "Active",
id : 00001
Table 2 and its name is "employee"
{
name : "Mike",
status : "Active",
id : 01,
company : {
name : "YYYY",
status : "Active",
id : 00001
}
},
{
name : "San",
status: "InActive",
id : 02,
company : {
name : "YYYY",
status : "Active",
id : 00001
}
}
I able to get the direct field as alias name in company table using the command
Company.aggregate([
{$match:{}},
{$project:{c_name:"$comp_name",id:1}}
])
but i can't acheive it the data in employers in company table which status is "Active"
My expected JSON is, Table one and its name is "company"
c_name : "YYYY",
emp : [
{
n : "Mike",
st : "Active",
id : 01
}
],
st : "Active",
id : 00001
Table 2 and its name is "employee"
{
n : "Mike",
st : "Active",
id : 01,
comp : {
n : "YYYY",
st : "Active",
id : 00001
}
}
Upvotes: 0
Views: 4992
Reputation: 3171
This would be for your company collection
db.company.aggregate([
{ $match:{ status: "Active"} }, // to only get the documents that have ths status
{ $unwind: "$employers"}, // to flatten your array
{ $match:{ "employers.status": "Active"} }, // match again for active employers
{ $project: { // for the final structure
c_name: "$comp_name",
emp: ["$employers"],
st: "$status",
id: 1
}
}
])
Upvotes: 1