gpt4 book ai didi

带有 $lookup 的 MongoDB 聚合仅包括(或投影)一些要从查询返回的字段

转载 作者:可可西里 更新时间:2023-11-01 09:16:24 24 4
gpt4 key购买 nike

在 mongo 中,在使用 $lookup 进行聚合之后,我希望请求只返回一些字段而不是整个文档。

我有以下查询:

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

此请求将返回给我:

{
"_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" : "mail@mail.com",
}
]
}

请求运行良好,但我想过滤 campaign.client 中的字段以仅获取例如 _idusername。有没有办法在 MongoDB aggregate 请求中执行此操作?

最佳答案

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

最终代码应该是:

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

关于带有 $lookup 的 MongoDB 聚合仅包括(或投影)一些要从查询返回的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41571730/

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