db.testA.aggregate([
{
"$lookup": {
"from": "testB",
"localField": "_id",
"foreignField": "aId",
"as": "join"
}
},
{
$project: {
count: {
$size: "$join"
}
}
},
{
$set: {
favorite: {
$switch: {
branches: [
{
case: {
$gte: [
"$count",
1
]
},
then: true
},
{
case: {
$gte: [
"$count",
0
]
},
then: false
},
],
default: false
}
}
}
}
])
I have this aggregation function. I would like to retain the fields, but I am not sure why they're gone.
db={
"testA": [
{
"_id": ObjectId("60508eeb52a2ab598a013bb9"),
"message": "hello",
"field1": false,
"field2": 1,
"field3": "something"
},
{
"_id": ObjectId("60508f2852a2ab598a013bba"),
"message": "hello",
"field1": false,
"field2": 1,
"field3": "something"
},
{
"_id": ObjectId("60508f2852a2ab665a013bba"),
"message": "hello",
"field1": false,
"field2": 1,
"field3": "something"
}
],
"testB": [
{
"_id": ObjectId("60508f4152a2ab598a013bbb"),
"aId": ObjectId("60508f2852a2ab598a013bba")
},
{
"_id": ObjectId("60508f4552a2ab598a013bbc"),
"aId": ObjectId("60508f2852a2ab598a013bba")
},
{
"_id": ObjectId("605090a452a2ab598a013bbd"),
"aId": ObjectId("60508eeb52a2ab598a013bb9")
}
]
}
This is my db. Essentially, I want the message, field1, field2, field3 to get piped through so that I get 6 fields instead of 2 at the end.
This is the result I get:
[
{
"_id": ObjectId("60508eeb52a2ab598a013bb9"),
"count": 1,
"favorite": true
},
{
"_id": ObjectId("60508f2852a2ab598a013bba"),
"count": 2,
"favorite": true
},
{
"_id": ObjectId("60508f2852a2ab665a013bba"),
"count": 0,
"favorite": false
}
]
https://mongoplayground.net/p/KjquoKCUw4P
This is what I want in case it's not clear:
[
{
"_id": ObjectId("60508eeb52a2ab598a013bb9"),
"count": 1,
"favorite": true,
"message": "hello",
"field1": false,
"field2": 1,
"field3": "something"
},
{
"_id": ObjectId("60508f2852a2ab598a013bba"),
"count": 2,
"favorite": true,
"message": "hello",
"field1": false,
"field2": 1,
"field3": "something"
},
{
"_id": ObjectId("60508f2852a2ab665a013bba"),
"count": 0,
"favorite": false,
"message": "hello",
"field1": false,
"field2": 1,
"field3": "something"
}
]
The data are almost the same, but assume they're all different.
CodePudding user response:
Use $addFields instead of $project:
{
$addFields: {
count: {
$size: "$join"
}
}
},