在mongo中,在使用aggregation
执行$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
中的字段,仅获取_id
和username
。有没有办法在MongoDB aggregate
请求中执行此操作?
答案 0 :(得分:34)
为了帮助其他人,@ 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
}
}
]);
答案 1 :(得分:4)
在pipeline
内使用$project
和$lookup
db.somecollection.aggregate([{
$lookup: {
from: "campaigns",
localField: "campId",
foreignField: "_id",
as: "campaign"
}
}, {
$unwind: "$campaign"
}, {
$lookup: {
from: "entities",
let: { client_id: "$campaign.clientid" },
pipeline : [
{ $match: { $expr: { $eq: [ "$_id", "$$client_id" ] } }, },
{ $project : { _id:1, username:1 } }
],
as: "campaign.client"
}
}]);
答案 2 :(得分:3)
只需在前面的答案中添加一些内容即可:您可以在要忽略的项目项上添加0,其余部分将被检索,因此您无需使用1:编写所有列表。 / p>
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": {
"campaign.client.shhh": 0
}
}
])
答案 3 :(得分:2)
我知道现在回答这个问题太晚了。但我认为,有时更新可能会非常有益。
项目阶段很棒,但是在$lookup
阶段,您仍然需要整个坞站。仅在紧随其后的投影阶段过滤字段。
MongoDB 3.6发布后,您现在可以将管道添加到$lookup
阶段,以指定多个联接条件。在他们的官方文档中找到更多详细信息。
Specify Multiple Join Conditions with $lookup
您可以按以下方式转换聚合管道,以获得所需的结果:
db.somecollection.aggregate([{
$lookup: {
from: "campaigns",
localField: "campId",
foreignField: "_id",
as: "campaign"
}
}, {
$unwind: "$campaign"
}, {
$lookup: {
from: "entities",
let: {clientid: '$campaign.clientid'},
pipeline: [
{ '$match':
{ '$expr':
{
'$eq': ['$_id', '$$clientid']
}
}
},
{ '$project':
'_id': 1,
'username': 1
}
]
as: "campaign.client"
}
}]);
这样,您可以在$lookup
阶段内过滤联接集合的字段。
注意内部管道的$$
阶段内的$match
符号。它用于表示在let
块中定义的自定义字段。