Reputation: 699
I have 2 collection, issues and repos.
issues : issue_id, body, full_name, ...
repos : repo_id, title, full_name, ...
I want to add "repo_id" field to issues collection. (with foreign field full_name)
After this process desired output collection;
issues2: issue_id, body, full_name, repo_id ...
db.getCollection("issues").aggregate([
{
$lookup: {
from: "repos",
localField: "full_name", // field in the orders collection
foreignField: "full_name", // field in the items collection
as: "fromissues"
}
},
{
$replaceRoot: { newRoot: { $mergeObjects: [ { $arrayElemAt: [ "$fromissues", 0 ] }, "$$ROOT" ] } }
},
{ $project: { fromissues: 0 } },
{$out: "issues2"}
])
I can use this query to merge 2 collection with whole fields. How can select only repo_id field? I tried to change this row but it didnt work.
{ $project: { "id":1, "full_name":1} },
If I use project, I must add to project "all columns of issues collection" + repo_id + full_name
{ $project: { "id":1, "body":1, ...(24 fields)... "repo_id":1 "full_name":1} },
Upvotes: 1
Views: 334
Reputation: 1080
Not use {$out: "issues2"} keyword in query
db.store.aggregate([
{
$lookup: {
from: "testers",
let: { item: "$fullName" },
pipeline: [
{ $match:
{ $expr:
{ $and:
[
{ $eq: [ "$fullName", "$$item" ] },
]
}
}
},
{ $project: { repo_id: 1 } }
],
as: "fromissues"
}
},
{
$replaceRoot: { newRoot: { $mergeObjects: [ { $arrayElemAt: [ "$fromissues", 0 ] }, "$$ROOT" ] } }
},
{ $project: { 'fromissues': 0 } },
])
Upvotes: 1