简体   繁体   English

Mongoose:使用子文档过滤器查找文档

[英]Mongoose : find document with subdocument filter

I have an User like so the id is NOT the _id )我有一个像这样的用户,所以id不是_id

{
  id: string;
}

Which can create files like so哪个可以像这样创建文件

{
  name: string;
  author: User;
}

I would like to get all Files where the author is a given User , but I do not know how to use the "filter" function to do that.我想获取作者是给定User的所有Files ,但我不知道如何使用“过滤器”function 来做到这一点。

So currently I do所以目前我做

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

Is there a more efficient way to do it?有没有更有效的方法来做到这一点?

(I use NestJS with the Mongoose integration, the syntax used is the same as the Mongoose library) (我使用带有 ZCCADCDEDB567ABAE643E15DCF0974E503Z 集成的 NestJS,使用的语法与 Mongoose 库相同)

EDIT编辑

Given the User document给定User文档

{
  _id: 'OVZVIbovibiugb44'
  id: 10
}

And the Files documentsFiles文件

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

I would like to use the function我想使用 function

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

And get, as a result,结果,得到,

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

You can use $lookup into an aggregation query to merge collections.您可以在aggregation查询中使用$lookup来合并 collections。

Also, as your id is an String and your author is an ObjectId you will need one previous stage using $toObjectId此外,由于您的id是一个字符串,而您的author是一个ObjectId ,您将需要使用$toObjectId的前一个阶段

So the query is similar to this:所以查询类似于:

  • $match stage (optional) to query only with documents you want. $match阶段(可选)仅查询您想要的文档。 Like a filter像一个过滤器
  • $project to convert id String field to ObjectId . $projectid String 字段转换为ObjectId You can user $set also.您也可以使用$set
  • $lookup to merge collection and the ouput is in a field called files . $lookup合并集合,输出位于名为files的字段中。
  • $project to output only files array from the merge. $project到 output 仅来自合并的files数组。
db.User.aggregate([
  { "$match": { "id": "5a934e000102030405000001" } },
  { "$project": { "id": { "$toObjectId": "$id" } } },
  { "$lookup": {
      "from": "Files",
      "localField": "id",
      "foreignField": "author",
      "as": "files" }
  },
  { "$project": { "files": 1 } }
])

Example here这里的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM