我想 $lookup 像 SQL Join 这样的远程集合,但使用 Mongo。而且我不希望将远程文档中的所有键都拉到原始集合中 - 只是一些特定的键。
这是我试过的:
[
{
$lookup: {
from: "tables",
localField: "type",
foreignField: "_id",
as: "type"
}
},
{
$unwind: "$type"
},
},
{
$project: {
"type.title": 1
}
}
]
然而,这仅打印“type.title”并忽略所有其他键,甚至来自原始文档。
有没有办法告诉 MongoDB 只从远程集合中提取特定字段?
最佳答案
您可以在 mongodb 3.6 及更高版本中使用以下聚合
[
{ "$lookup": {
"from": "tables",
"let": { "type": "$type" },
"pipeline": [
{ "$addFields": { "owners": { "$cond": { "if": { "$ne": [ { "$type": "$owners" }, "array" ] }, "then": [], "else": "$owners" } } }},
{ "$match": { "$expr": { "$eq": ["$_id", "$$type"] }}},
{ "$project": { "title": 1 }}
],
"as": "type"
}},
{ "$unwind": "$type" }
]
关于database - MongoDB 如何从$lookup 远程集合中$project(限制字段)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54055254/