首页 文章

mongoDB中的字段名称别名

提问于
浏览
0

我正在使用mongoDB和new to native命令,我喜欢使用别名来表示字段名称

在这里我使用两个表(公司和员工),在公司表中,员工字段与多个对应关联

我的实际JSON如下 . 表一及其名称是“公司”

comp_name : "YYYY",
employers : [
                {
                    name : "Mike",
                    status : "Active",
                    id : 01
                },{
                    name : "San",
                    status: "InActive",
                    id : 02
                }
            ],
status : "Active",
id : 00001

表2及其名称为“员工”

{
    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
            }
}

我可以使用该命令将直接字段作为别名在公司表中获取

Company.aggregate([
    {$match:{}},
    {$project:{c_name:"$comp_name",id:1}}
])

但我无法实现公司表中雇主的数据状态为“活跃”

我期望的JSON是,表一,它的名字是“公司”

c_name : "YYYY",
emp : [
                {
                    n : "Mike",
                    st : "Active",
                    id : 01
                }
            ],
st : "Active",
id : 00001

表2及其名称为“员工”

{
    n : "Mike",
    st : "Active",
    id : 01,
    comp : {
                n : "YYYY",
                st : "Active",
                id : 00001
            }
}

1 回答

  • 1

    这将是您公司的收藏

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

相关问题