Reputation: 211
I need help for querying mongoDb
So I have two collections like
Collection A:
{someField: "123", anotherField: "456"},
{someField: "1234", anotherField: "4567"}
Collection B
{someField: "123", otherField: "789"}
with Query:
db.A.aggregate([
{
$lookup:
{
from: "B",
let: { someField: "$someField", otherField: "$otherField" },
pipeline: [
{ $match:
{ $expr:
{ $and:
[
{ $eq: [ "$someField", "$$someField" ] },
{ $eq: [ "$otherField", "789" ] }
]
}
}
},
],
as: "B"
}
}
])
I get all collection A, with B empty in {someField: "1234", anotherField: "4567"}
What I want to achieve is like:
{someField: "123", anotherField: "456", b: {someField: "123", otherField: "789"}}
Thank you in advance
Upvotes: 2
Views: 103
Reputation: 5669
you only need to declare $someField
in the let section.
db.collectionA.aggregate([
{
$lookup: {
from: 'collectionB',
let: { some_field: '$someField' },
pipeline: [
{ $match: {
$expr: {
$and: [
{ $eq: [ "$someField", "$$some_field" ] },
{ $eq: [ "$otherField", "789" ] }
]
}
}
}
],
as: 'B'
}
},
{
$match: {
$expr: {
$gt: [ { $size: "$B" }, 0 ]
}
}
}
])
https://mongoplayground.net/p/RTiUMWl8QaX
Upvotes: 2
Reputation: 14287
This is how I removed the empty B
array documents:
db.A.aggregate( [
{
$lookup: {
from: "B",
localField: "someField",
foreignField: "someField",
as: "B"
}
},
{
$addFields: {
B: {
$filter: {
input: "$B",
cond: {
$eq: [ "$$this.otherField", "789" ]
}
}
}
}
},
{
$match: {
$expr: {
$gt: [ { $size: "$B" }, 0 ]
}
}
}
] ).pretty()
Upvotes: 1