gpt4 book ai didi

javascript - mongoDB 中的字段名称别名

转载 作者:行者123 更新时间:2023-12-03 02:51:52 28 4
gpt4 key购买 nike

我正在使用 mongoDB,并且是 native 命令的新手,我喜欢使用别名作为字段名称

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

我的实际 JSON 如下。表一,名称为“公司”

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

表2及其名称为“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
}
}

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

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及其名称为“employee”

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

最佳答案

这将供您公司收藏

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

关于javascript - mongoDB 中的字段名称别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47813986/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com