找到父文档后如何查询mongoDB子文档

时间:2020-12-27 16:29:21

标签: javascript mongodb mongoose

我正在尝试使用 mongoose 在我的 mongoDB 数据库中查询 特定 文档的子文档。我想首先运行查询以获取特定用户文档,然后查询一组子文档以找到与特定 id 匹配的文档。

这里给出一些上下文是我的数据结构

enter image description here

每个文档都是针对特定用户的,articleVotes 子文档包含他们投票支持的文章。在使用我的 Usermongoose 模型通过 User.findOne({_id: req.user._id)) 查找当前用户文档后,我想通过执行类似 findOne({_id: articleId, voteType: "1"}) 的操作来检查他们是否已经对特定文章投了赞成票。然而,因为它是一个子文档,我正在努力弄清楚如何做到这一点。有人可以解释一下我该怎么做吗?

1 个答案:

答案 0 :(得分:1)

您可以使用 $filter 运算符,

MongoDB v4.4 支持 findOne()

  • $filter 在投影中迭代 atricleVotes 数组的循环并使用条件 articleIdvoteType 进行过滤
db.collection.findOne({
  _id: req.user._id,
  "atricleVotes.articleId": articleId
},
{
  _id: 1,
  atricleVotes: {
    $filter: {
      input: "$atricleVotes",
      cond: {
        $and: [
          { $eq: ["$$this.articleId", articleId] },
          { $eq: ["$$this.voteType", 1] }
        ]
      }
    }
  }
})

Playground


MongoDB v3.2 或更高版本

  • $match 你有条件
  • $addFields 获得相同的 $filter 操作并得到过滤 atricleVotes
db.collection.aggregate([
  {
    $match: {
      _id: req.user._id,
      "atricleVotes.articleId": articleId
    }
  },
  {
    $addFields: {
      atricleVotes: {
        $filter: {
          input: "$atricleVotes",
          cond: {
            $and: [
              { $eq: ["$$this.articleId", articleId] },
              { $eq: ["$$this.voteType", 1] }
            ]
          }
        }
      }
    }
  }
])

Playground