简体   繁体   中英

How to query a mongoDB subdocument after finding the parent document

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?

You can use $filter operator,

MongoDB v4.4 to support in 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] }
        ]
      }
    }
  }
})

Playground


MongoDB v3.2 or Above

  • $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] }
            ]
          }
        }
      }
    }
  }
])

Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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