在查找操作之后隐藏嵌套文档中的_id

问题描述 投票:1回答:2

我试图隐藏嵌套文档中的_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"
    }
}}
mongodb mongodb-query aggregation-framework
2个回答
1
投票

再添加一个投影阶段:

{
    $project: {
      "from._id": false,
      "to._id": false
    }
} 

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

 }
}
© www.soinside.com 2019 - 2024. All rights reserved.