Hi,
I have the following data:
db={
"accounts": [
{
"_id": {
"$oid": "644798f79ad5e97dd4296152"
},
"name": "The James Trust",
"schools:": [
{
"_id": {
"$oid": "6447998d9ad5e97dd429615a"
},
"name": "Jamestown Academy"
},
{
"_id": {
"$oid": "644799d99ad5e97dd4296161"
},
"name": "Jamestown College"
}
]
}
],
"users": [
{
"_id": {
"$oid": "63e27b3483161a984f19fcce"
},
"accountId": {
"$oid": "644798f79ad5e97dd4296152"
},
"name": "James Boing",
"email": "james@whatever.boing",
"schools": [
{
"roles": [
"admin",
"safeguard"
],
"schoolId": {
"$oid": "6447998d9ad5e97dd429615a"
}
},
{
"roles": [
"staff"
],
"schoolId": {
"$oid": "644799d99ad5e97dd4296161"
}
}
]
}
]
}
I don’t seem to be able to use the $account.schools reference in the following example:
db.users.aggregate([
{
$match: {
_id: ObjectId("63e27b3483161a984f19fcce")
}
},
{
$lookup: {
from: "accounts",
localField: "accountId",
foreignField: "_id",
as: "account"
}
},
{
$unwind: {
path: "$account"
}
},
{
$addFields: {
z: {
$arrayElemAt: [
"$account.schools",
0
]
}
}
}
])
Instead, I always get null
for z
. I think I’m missing something fundamental here in the way that $unwind is operating. I’m only using $unwind to flatten the array because it’s a 1-1 relationship between a user and an account.
I’ve been stuck for hours on this, and any help would be appreciated.