Reputation: 647
I am trying to query a subdocument of a specific document in my mongoDB database using mongoose. I would like to first run a query to get a specific users document, and then subsequently query an array of subdocuments to find one which matches a specific id.
To give some context here is my data structure
Each document is for a specific user, and the articleVotes
subdocument contains articles they have voted for. After using my User
mongoose model to find the current users document via User.findOne({_id: req.user._id))
, i want to then check if they have up-voted a specific article yet, by doing something like findOne({_id: articleId, voteType: "1"})
. However, because it's a subdocument i'm stuggling to work out how to do this. Can someone explain how i can do this?
Upvotes: 3
Views: 819
Reputation: 36104
You can use $filter operator,
findOne()
$filter
in projection to iterate loop of atricleVotes
array and filter using condition articleId
and 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] }
]
}
}
}
})
$match
you conditions$addFields
to get same $filter operation and get filtered 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] }
]
}
}
}
}
}
])
Upvotes: 3