如何在MongoDB中查询引用的对象

时间:2020-11-03 10:52:51

标签: reactjs mongodb graphql

我的mongo数据库中有两个馆藏:图书和作者

Book集合具有一个author字段,该字段引用了创建它的作者

const schema = new mongoose.Schema({
  ...
  author: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Author'  
})

我正在使用graphql,而我当前的代码如下所示。 booksByAuthor是一个查询,输入名称,然后返回该作者写的书。(此方法可以正常工作,并提供正确的输出)

booksByAuthor: async (root) => {
  const author = await Author.findOne({name: root.name})
  
  return await Book.find({
    author: author._id
  })
}

我当前的实现方式首先查询Author集合,然后使用作者的ID来查询Book集合。但是,我觉得必须有一种方法可以不经过Author集合。

理想情况下,我希望它是这样的:(伪代码)

return await Book.find({
   author.name: {root.name}

})

我尝试做

  return await Book.find({
    "author.name": { $in: [root.name] }
  })

  return await Book.find({
    name: { author: { $in: [root.name] } }
  })

,但是都返回一个空数组。我不知道我是否应该在这种情况下使用$ in

1 个答案:

答案 0 :(得分:0)

您可以使用$lookup在单个查询中实现此目的。 $lookup与sql中的joins类似。

根据您的问题,我创建了一些示例文档。以下是按作者获取书籍的查询。

db.book.aggregate([
  {
    "$lookup": {
      "from": "author",
      "localField": "author",
      "foreignField": "_id",
      "as": "author"
    }
  },
  {
    "$match": {
      "author.name": "Kafka"
    }
  }
])

这里是Mongo Playground。请点击链接查看正在执行的查询。您还将能够看到我使用过的样本文档。可以根据需要随意使用它。