如何为多个集合创建mongodb聚合查询

如何为多个集合创建mongodb聚合查询,mongodb,aggregate,Mongodb,Aggregate,我有两种型号 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, requir

我有两种型号

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 ....."
  },
  ...
]
  public async getStoriesList(): Promise<Story[]> {
    return await this.storyModel.aggregate([{
      $lookup: {
        from: 'texts',
        localField: 'texts',
        foreignField: 'textKey',
        as: 'texts',
      },
    }]);
  }
我想将集合
text
中的字段
textKey
与集合
story
中的数组
text
相结合,并将集合
text
中的字段
text
写入结果查询。我必须得到一个对象数组

[
  {
     "type": "export",
     "texts": ["Export .....", "Download ....."]
  },
  ...
]
我尝试创建多个集合的聚合

// stories
[
  {
    "type": "export",
    "texts": ["export", "download"]
  },
  ...
]

// Text
[
  {
    "textKey": "export",
    "text": "Export ....."
  },
  {
    "textKey": "download",
    "text": "Download ....."
  },
  ...
]
  public async getStoriesList(): Promise<Story[]> {
    return await this.storyModel.aggregate([{
      $lookup: {
        from: 'texts',
        localField: 'texts',
        foreignField: 'textKey',
        as: 'texts',
      },
    }]);
  }
公共异步getStoriesList():Promise{ return wait this.storyModel.aggregate([{ $lookup:{ 来自:“文本”, localField:'文本', foreignField:'textKey', 如:‘文本’, }, }]); }
但我得到了一个空数组。我哪里出错了?如何创建聚合?

您无法对数组进行
查找
,您可以使用此聚合实现所需的功能,但如果您有大的集合,则可能会很慢:

db.stories.aggregate([
{
“$unwind”:“$texts”
},
{
“$lookup”:{
“来自”:“文本”,
“localField”:“text”,
“foreignField”:“textKey”,
“as”:“数据”
}
},
{
“$unwind”:“$data”
},
{
“$group”:{
“_id”:“类型”,
“案文”:{
“$push”:“$data.text”
}
}
},
{
“$project”:{
“类型”:“$\u id”,
“_id”:0,
“文本”:1
}
}
])