mongodb从另一个查询中获取值



我有两个集合

  • 保存以下用户的集合
  • 用户故事的集合

我只想看到我关注过的用户的故事

这是我的数据库的一个例子

db = {
"follow": [
{
"_id": 1,
"start": "user1",
"end": "user2",

},
{
"_id": 2,
"start": "user2",
"end": "user3",

}
],
"story": [
{
"_id": 1,
"owner_id": "user2",
"updated_at": 1638090000,
"deleted_at": null
},
{
"_id": 2,
"owner_id": "user3",
"updated_at": 1638080000,
"deleted_at": null
}
]
}

我想要这样一个查询。当然,这是错误的:

db.story.aggregate([
{
"$match": {
"deleted_at": null,
"updated_at": {
$gte: 1638081000
},
"owner_id": {
$in: [
db.follow.find({"start": "user1"})
]
}
}
}
])

请注意,我希望所有这些都在一个查询中完成

查询mongoplayground: https://mongoplayground.net/p/ysRUDW4hRzh

这里应该使用$lookup

db.follow.aggregate([
{
"$match": {
"start": "user2"
}
},
{
$lookup: {
from: "story",
localField: "end",
foreignField: "owner_id",
pipeline: [],
as: "stories",
}
},

])

这个查询查找故事数据库,其中localField(在这种情况下是end)等于foreignField(在这种情况下是owner_id),然后添加一个故事字段

结果:https://mongoplayground.net/p/0M6YxYWAQ2n

最新更新