Select a specific element from nested array after update

I have a schema which looks like the following:

{
    "...fields"
    "profile": {
        "past_exams": [
            {
                "_id": "....",
                "details": "..."
            },
            {
                "_id": "....",
                "details": "..."
            }
        ]
    }
}

and I am trying to select a specific element from the array past_exams but i keep getting an error : MongoServerError: Cannot use $elemMatch projection on a nested field.

Here is my code:

const profile = await this.userModel.findOneAndUpdate({
            'profile._id': profileId,
        },
            updateContent,
            {
                arrayFilters: [{ "pastExam._id": new Types.ObjectId(pastExamId) }],
                new: true,
                runValidators: true,
                fields: {
                    "profile.past_exams": {
                        $elemMatch: {
                            _id: new Types.ObjectId(pastExamId)
                        }
                    }
                },
            }
        );

I am not sure what I am doing wrong. I essentially want the updated element from the array to return to the requester after the query is done.

Hello @Awakening_Quasar,

As the error said, it will not support $elemMatch in the nested property.

You can use $filter operator,

  "fields": {
    "profile.past_exams": {
      "$filter": {
        "input": "$profile.past_exams",
        "cond": {
          "$eq": [
            "$$this._id",
            new Types.ObjectId(pastExamId)
          ]
        }
      }
    }
  }

Hey there @turivishal. Is it a mongo limitation or was I using the wrong operator for this?

I won’t say limitation but $elemMatch does not support in nested property.

Well, there is a backlog pending status similar to your case, I hope they implement it soon.
You should log in and vote for this feature in this backlog.
https://jira.mongodb.org/browse/SERVER-7625

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.