【问题标题】:How to query a mongoDB subdocument after finding the parent document找到父文档后如何查询mongoDB子文档
【发布时间】:2021-04-04 15:39:50
【问题描述】:
我正在尝试使用 mongoose 在我的 mongoDB 数据库中查询 特定 文档的子文档。我想先运行一个查询来获取特定的用户文档,然后再查询一组子文档以找到与特定 id 匹配的子文档。
这里给出一些上下文是我的数据结构
每个文档都针对特定用户,articleVotes 子文档包含他们投票支持的文章。在使用我的Usermongoose 模型通过User.findOne({_id: req.user._id)) 查找当前用户文档后,我想通过执行findOne({_id: articleId, voteType: "1"}) 之类的操作来检查他们是否对特定文章进行了投票。但是,因为它是一个子文档,我正在努力研究如何做到这一点。有人可以解释一下我该怎么做吗?
【问题讨论】:
标签:
javascript
mongodb
mongoose
【解决方案1】:
您可以使用$filter 运算符,
MongoDB v4.4 支持findOne()
-
$filter 在投影中迭代 atricleVotes 数组的循环并使用条件 articleId 和 voteType 进行过滤
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