olips
olips

Reputation: 13

Get mongoose object of an array within another object of array

I have this document in my mongodb collection:

        "_id": "62be0271d373b2f2fc1826a2",
        "condition": "new",
        "variants": [
            {
                "color_name": "Green",
                "items": [
                    {
                        "size": "S",
                        "price": 100,
                        "quantity": 1,
                        "_id": "62be0271d373b2f2fc1826a4"
                    },
                    {
                        "size": "M",
                        "price": 100,
                        "quantity": 2,
                        "_id": "62be0271d373b2f2fc1826a5"
                    }
                ],
                "_id": "62be0271d373b2f2fc1826a3"
            },
            {
                "color_name": "Blue",
                "items": [
                    {
                        "size": "S",
                        "price": 100,
                        "quantity": 1,
                        "_id": "62be0271d373b2f2fc1826a7"
                    },
                    {
                        "size": "S",
                        "price": 100,
                        "quantity": 1,
                        "_id": "62be0271d373b2f2fc1826a8"
                    }
                ],
                "_id": "62be0271d373b2f2fc1826a6"
            }
        ],
        "featured": true

I want to get only the first variant with it's _id = "62be0271d373b2f2fc1826a3" and also with it's second items that has this "_id": "62be0271d373b2f2fc1826a5", don't show other fields.

NOTE: there are more objects like this in the collection so loop through and match all and retrieve only fields matched.

Upvotes: 1

Views: 41

Answers (1)

nimrod serok
nimrod serok

Reputation: 16033

One option is using $filter:

db.collection.aggregate([
  {
    $project: {
      variants: {
        $first: {
          $filter: {
            input: "$variants",
            cond: {
              $eq: [
                "$$this._id",
                "62be0271d373b2f2fc1826a3"
              ]
            }
          }
        }
      },
      _id: 0
    }
  },
  {
    $set: {
      "variants.items": {
        $filter: {
          input: "$variants.items",
          cond: {
            $eq: [
              "$$this._id",
              "62be0271d373b2f2fc1826a5"
            ]
          }
        }
      },
      _id: "$$REMOVE"
    }
  }
])

See how it works on the playground example

Upvotes: 1

Related Questions