首页 > 解决方案 > Mongoose:使用子文档过滤器查找文档

问题描述

我有一个像这样的用户id不是)_id

{
  id: string;
}

哪个可以像这样创建文件

{
  name: string;
  author: User;
}

我想得到所有Files给定作者的地方User,但我不知道如何使用“过滤器”功能来做到这一点。

所以目前我做

const author = await this.userModel.find({ id });
return this.filesModel.find({ author });

有没有更有效的方法来做到这一点?

(我使用 NestJS 与 Mongoose 集成,使用的语法与 Mongoose 库相同)

编辑

鉴于User文件

{
  _id: 'OVZVIbovibiugb44'
  id: 10
}

Files文件

[
  { name: "1.docx", author: ObjectId('OVZVIbovibiugb44') },
  { name: "2.docx", author: ObjectId('voisbvOVISBEIVBv') },
]

我想使用该功能

findOwned(authorId = 10) {
  const author = await this.userModel.find({ id });
  return this.filesModel.find({ author });
  // But do it only with "filesModel"
}

结果,得到,

[
  { name: '1.docx', author: 'ObjectId('OVZVIbovibiugb44') },
]

标签: javascriptmongodbmongoose

解决方案


您可以使用$lookupintoaggregation查询来合并集合。

此外,由于您id是一个字符串,而您author是一个,ObjectId您将需要使用前一个阶段$toObjectId

所以查询类似于:

  • $match阶段(可选)仅查询您想要的文档。像一个过滤器
  • $projectid字符串字段转换为ObjectId. 你也可以用户$set
  • $lookup合并集合,输出位于名为files.
  • $projectfiles从合并中仅输出数组。
db.User.aggregate([
  { "$match": { "id": "5a934e000102030405000001" } },
  { "$project": { "id": { "$toObjectId": "$id" } } },
  { "$lookup": {
      "from": "Files",
      "localField": "id",
      "foreignField": "author",
      "as": "files" }
  },
  { "$project": { "files": 1 } }
])

这里的例子


推荐阅读