MongoDB 聚合与 $lookup 限制某些字段从查询返回

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35583569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 20:39:42  来源:igfitidea点击:

MongoDB aggregation with $lookup limit some fields to return from query

mongodbaggregation-frameworklookup

提问by Samuel Rondeau-Millaire

In mongo, after doing an aggregationwith $lookup, I would like the request to return only some fields and not the whole document.

在 mongo 中,在执行aggregationwith 之后$lookup,我希望请求仅返回某些字段而不是整个文档。

I have the following query :

我有以下查询:

db.somecollection.aggregate([{
    $lookup: {
        from: "campaigns",
        localField: "campId",
        foreignField: "_id",
        as: "campaign"
    }
}, {
    $unwind: "$campaign"
}, {
    $lookup: {
        from: "entities",
        localField: "campaign.clientid",
        foreignField: "_id",
        as: "campaign.client"
    }
}]);

This request will return me this :

此请求将返回给我:

{
"_id" : ObjectId("56cc7cd1cc2cf62803ebfdc7"),
"campId" : ObjectId("56c740e4479f46e402efda84"),
"articleId" : ObjectId("56c742c06094640103ba3843"),
"campaign" : {
    "_id" : ObjectId("56c740e4479f46e402efda84"),
    "clientid" : ObjectId("56c740b8479f46e402efda83"),
    "client" : [
        {
            "_id" : ObjectId("56c740b8479f46e402efda83"),
            "username" : "someusername",
            "shhh" : "somehashedpassword",
            "email" : "[email protected]",
        }
    ]
}

The request works well, but I would like to filter the fields in campaign.clientto only get for example _idand username. Is there a way to do this in a MongoDB aggregaterequest?

该请求运行良好,但我想过滤字段campaign.client以仅获取例如_idusername. 有没有办法在 MongoDBaggregate请求中做到这一点?

回答by Rodrigo Lopetegui

Just to help others with this, @SiddhartAjmera has the right answer, I only needed to add double quotes for nested values like "campaign.clientid".

只是为了帮助其他人,@SiddhartAjmera 有正确的答案,我只需要为“campaign.clientid”等嵌套值添加双引号。

The final code should be:

最终的代码应该是:

db.somecollection.aggregate([
      {
        "$lookup": {
          "from": "campaigns",
          "localField": "campId",
          "foreignField": "_id",
          "as": "campaign"
        }
      },
      {
        "$unwind": "$campaign"
      },
      {
        "$lookup": {
          "from": "entities",
          "localField": "campaign.clientid",
          "foreignField": "_id",
          "as": "campaign.client"
        }
      },
      {
        "$project": {
          "_id": 1,
          "campId": 1,
          "articleId": 1,
          "campaign._id": 1,
          "campaign.clientid": 1,
          "campaign.client._id": 1,
          "campaign.client.username": 1
        }
      }
]);