I want to make aggregation pipeline in MongoDB v4.4.
I have two collections.
userscollection[ { _id: "user1", username: "john" }, { _id: "user2", username: "bob" }, ]articlescollection[ { _id: "article1", view_history: [ { user: "user1", viewed_at: ISODate("...") }, { user: "user2", viewed_at: ISODate("...") }, { user: "user1", viewed_at: ISODate("...") }, ] } ]
My desired result after running aggregation on articles collection is:
[
{
_id: "article1",
view_history: [
{ user: "john", viewed_at: ISODate("...") },
{ user: "bob", viewed_at: ISODate("...") },
{ user: "john", viewed_at: ISODate("...") },
]
}
]
So user fields on each history item in view_history are substituted with the user's username.
I tried many answers on SO, but can't find any solution for my situation. Here's what I got so far:
db.articles.aggregate([
{
$lookup: {
from: "users",
localField: "view_history.user",
foreignField: "_id",
as: "output",
}
}
])
Which yields:
[
{
_id: "article1",
view_history: [
{ user: "user1", viewed_at: ISODate("...") },
{ user: "user2", viewed_at: ISODate("...") },
{ user: "user1", viewed_at: ISODate("...") },
],
output: [
{ _id: "user1", username: "john" },
{ _id: "user2", username: "bob" },
]
}
]
(There's only one user1 in output, and viewed_at not included)