首页 > 解决方案 > 如何为多个集合创建 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字段写入结果查询。我必须得到一个对象数组texttext

[
  {
     "type": "export",
     "texts": ["Export .....", "Download ....."]
  },
  ...
]

我试图创建一个聚合多个集合

  public async getStoriesList(): Promise<Story[]> {
    return await this.storyModel.aggregate([{
      $lookup: {
        from: 'texts',
        localField: 'texts',
        foreignField: 'textKey',
        as: 'texts',
      },
    }]);
  }

但我有一个空数组。我在哪里犯了错误?如何创建聚合?

标签: mongodbaggregate

解决方案


你不能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
    }
  }
])

推荐阅读