[Fixed] Use Mongoose aggregate to fetch object inside of an array

Issue

Here is my MongoDB schema:

 {
            "_id": "603f23ff6c1d862e5ced9e35",
            "reviews": [
                {
                    "like": 0,
                    "dislike": 0,
                    "_id": "603f23ff6c1d862e5ced9e34",
                    "userID": "5fd864abb53d452e0cbb5ef0",
                    "comment": "Not so good",
                },
                {
                    "like": 0,
                    "dislike": 0,
                    "_id": "603f242a6c1d862e5ced9e36",
                    "userID": "5fd864abb53d452e0cbb5ef0",
                    "comment": "Not so good",
                }
]
productID:"hdy6nch99dndn"
}

I want to use aggregate to get the review object of a particular id. I tried but not with any success.

Here is my code:

  ProductReview.aggregate([
    { $match: { productID: productID } }
 ])

Solution

$match
$unwind

db.collection.aggregate([
  {
    $match: {
      productID: 1
    }
  },
  {
    $unwind: "$reviews"
  },
  {
    $match: {
      "reviews._id": 2
    }
  }
])

Output:

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "productID": 1,
    "reviews": {
      "_id": 2,
      "comment": "second comment",
      "dislikes": [
        {
          "userID": 3
        },
        {
          "userID": 4
        }
      ],
      "likes": [
        {
          "userID": 1
        },
        {
          "userID": 2
        }
      ]
    }
  }
]

Mongo Playground: https://mongoplayground.net/p/qfWS1rCuMfc

Leave a Reply

(*) Required, Your email will not be published