Home > OS >  Get mongoose object of an array within another object of array
Get mongoose object of an array within another object of array

Time:07-05

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.

CodePudding user response:

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

  • Related