S
S
sldo_ru2020-05-10 22:22:59
MongoDB
sldo_ru, 2020-05-10 22:22:59

How to find an entry in a nested array of MongoDB objects?

Good evening, there is a record. It is necessary to find a user with ID 1, and extract an object with _id 24123123dsfasdf32 from his items field

{
    id: 1,
    items: [
        {
            _id: 24123123dsfasdf32,
            text: 'string'
        }
    ]
},
{
    id: 2,
    items: [
        {
            _id: 2sdfsdfsdf4123123dsfasdf32,
            text: 'string2'
        }
    ]
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
sldo_ru, 2020-05-11
@sldo_ru

To solve the problem, it is enough to use $elemMatch. For the current model it will be like this:

Model.findOne({id: 1}, {items: {$elemMatch: {_id: 24123123dsfasdf32}}).

The resulting object can already be parsed by fields.

R
RaShe, 2020-05-10
@RaShe

find('items._id': 24123123dsfasdf32)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question