kittu
kittu

Reputation: 7018

How to get one object from array of objects based on id in mongoose

I have data like this:

{
    "global": {
        "summaryNotificationSchedule": {
            "weekDay": ["wednesday"]
        }
    },
    "userEmail": "[email protected]",
    "environments": [
        {
            "userPreference": {
                "summaryNotificationSchedule": {
                    "weekDay": ["friday"]
                }
            },
            "envId": "u1"
        },
        {
            "userPreference": {
                "summaryNotificationSchedule": {
                    "weekDay": ["tuesday"],
                }
            },
            "envId": "u2"
        }
    ]
}

and I need to get userPreference object from environments array based on envId.

Tried this but its returning complete array but I need to return object inside the array i.e. userPreference

const envData = await preferencesModel.findOne({ userEmail, "environments.envId": envId }, { 'environments.$.envId': envId }).lean();

Upvotes: 1

Views: 71

Answers (2)

Dĵ ΝιΓΞΗΛψΚ
Dĵ ΝιΓΞΗΛψΚ

Reputation: 5689

give the following a go:

find query:

db.collection.findOne(
    {
        userEmail: "[email protected]",
    },
    {
        environments: {
            $elemMatch: {
                envId: "u1"
            }
        }
    }
)

aggregation pipeline:

db.collection.aggregate([
    {
        $match: {
            userEmail: "[email protected]"
        }
    },
    {
        $set: {
            environments: {
                $first: {
                    $filter: {
                        input: "$environments",
                        cond: { $eq: ["$$this.envId", "u1"] }
                    }
                }

            }
        }
    },
    {
        $replaceWith: "$environments.userPreference"
    }
])

Upvotes: 1

varman
varman

Reputation: 8894

You can use positional operator. But be ware to use postional operator in projection

db.collection.find({
  "environments.envId": "u2"
},
{
  "environments.userPreference.$": 1
})

Working Mongo playground

Update 1,

The output is As you expected

[
  {
    $project: {
      environments: {
        $filter: {
          input: "$environments",
          cond: {
            $eq: [
              "$$this.envId",
              "u1"
            ]
          }
        }
      }
    }
  },
  {
    $project: {
      userPreference: {
        $ifNull: [
          {
            $arrayElemAt: [
              "$environments.userPreference",
              0
            ]
          },
          {}
        ]
      }
    }
  }
]

Working Mongo playground

Upvotes: 1

Related Questions