我试图隐藏嵌套文档中的_id值,但我无法实现正确的语法。无论我如何尝试,我总是会遇到错误。
我的实际代码:
db.integration.aggregate([
{
$match: {"integration_name" : "a-to-b" }
},
{
$lookup:
{
from: "service",
localField: "from",
foreignField: "_id",
as: "from"
}
},
{
$lookup:
{
from: "service",
localField: "to",
foreignField: "_id",
as: "to"
}
},
{
$project: {
_id: false,
integration_name: true,
from: { $arrayElemAt: ["$from",0]},
to: { $arrayElemAt: ["$to",0]},
inbound_settings: true,
outbound_settings: true
}
}])
实际输出:
{
"integration_name" : "a-to-b",
"inbound_settings" : {
"pattern_matching" : "*.xml",
"polling_frequency" : 1000.0,
"backup_directory" : "/backup"
},
"outbound_settings" : {
"pattern_matching" : "*.xml",
"polling_frequency" : 1000.0,
"backup_directory" : "/backup"
},
"from" : {
"_id" : ObjectId("5a9821f02c669a3c40bd2a63"),
"name" : "a",
"connection_details" : {
"protocol" : "ftp",
"host" : "localhost",
"port" : 21.0,
"path" : "/Users/rabobank/files/",
"user" : "rabobank",
"password" : "rabobank"
}
},
"to" : {
"_id" : ObjectId("5a9821e32c669a3c40bd2a62"),
"name" : "b",
"connection_details" : {
"protocol" : "ftp",
"host" : "localhost",
"port" : 22.0,
"path" : "/Users/deutschebank/files/",
"user" : "deutschebank",
"password" : "deutschebank"
}
}}
“from”和“to”字段都是嵌套文档。我想要实现的是隐藏from._id和to._id值。
预期产出:
{
"integration_name" : "a-to-b",
"inbound_settings" : {
"pattern_matching" : "*.xml",
"polling_frequency" : 1000.0,
"backup_directory" : "/backup"
},
"outbound_settings" : {
"pattern_matching" : "*.xml",
"polling_frequency" : 1000.0,
"backup_directory" : "/backup"
},
"from" : {
"name" : "a",
"connection_details" : {
"protocol" : "ftp",
"host" : "localhost",
"port" : 21.0,
"path" : "/Users/rabobank/files/",
"user" : "rabobank",
"password" : "rabobank"
}
},
"to" : {
"name" : "b",
"connection_details" : {
"protocol" : "ftp",
"host" : "localhost",
"port" : 22.0,
"path" : "/Users/deutschebank/files/",
"user" : "deutschebank",
"password" : "deutschebank"
}
}}
答案 0 :(得分:1)
再添加一个投影阶段:
{
$project: {
"from._id": false,
"to._id": false
}
}
答案 1 :(得分:0)
您需要设置_id: 0
,而案例查询中的$project
应如下所示,您还可以设置FromId: '$from._id', ToId: '$to._id'
{
$project: {
'to._id': 0,
'from._id': 0,
'FromId': '$from._id', //It's optional
'ToId': '$to._id' //It's optional
}
}