mongodb - 如何为多个集合创建 mongodb 聚合查询
问题描述
我有两个模型
export const StorySchema = new Schema({
type: { type: String, required: true },
texts: { type: Array, require: true },
});
export const TextSchema = new Schema({
textKey: { type: String, required: true },
text: { type: String, required: true },
});
我的收藏
// stories
[
{
"type": "export",
"texts": ["export", "download"]
},
...
]
// Text
[
{
"textKey": "export",
"text": "Export ....."
},
{
"textKey": "download",
"text": "Download ....."
},
...
]
我想将集合中的字段与textKey
集合text
中的数组结合起来,并将texts
集合中的story
字段写入结果查询。我必须得到一个对象数组text
text
[
{
"type": "export",
"texts": ["Export .....", "Download ....."]
},
...
]
我试图创建一个聚合多个集合
public async getStoriesList(): Promise<Story[]> {
return await this.storyModel.aggregate([{
$lookup: {
from: 'texts',
localField: 'texts',
foreignField: 'textKey',
as: 'texts',
},
}]);
}
但我有一个空数组。我在哪里犯了错误?如何创建聚合?
解决方案
你不能lookup
在一个数组上,你可以使用这个聚合来实现你想要的,但是如果你有大集合,它可能会很慢:
db.stories.aggregate([
{
"$unwind": "$texts"
},
{
"$lookup": {
"from": "texts",
"localField": "texts",
"foreignField": "textKey",
"as": "data"
}
},
{
"$unwind": "$data"
},
{
"$group": {
"_id": "type",
"texts": {
"$push": "$data.text"
}
}
},
{
"$project": {
"type": "$_id",
"_id": 0,
"texts": 1
}
}
])
推荐阅读
- python - python pandas read_excel(filename) 但我在真实文件名之前找到了 '~$'
- javascript - 当我将堆栈拆分为数组时,错误堆栈显示不同的信息
- html - 从网页处理 linux 用户密码过期
- c# - 在 C# 中使用 DI 登录到控制台
- intellij-idea - 如何替换 intellij 中的整行代码,其中行以公共前缀开头
- html - 没有 /public 后缀,Laravel 网页无法工作
- c# - 获取数组中字符串的索引列表?
- watchkit - WatchConnectivity transferFile 问题(手表-> iphone)
- javascript - 加载网页后是否可以禁用 JS 插件?
- c# - 如何识别 ChromeDriver 启动的 Chrome 进程?