S
S
sldo_ru2020-05-10 19:10:38
MongoDB
sldo_ru, 2020-05-10 19:10:38

How to find element in nesting and delete in MongoDB?

Good evening! Searched for an answer but didn't find it. Help me please.

There is a user model:

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


It is necessary to find a user with ID 1, then find and delete an object with _id 24123123dsfasdf32 from him in the items array

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hzzzzl, 2020-05-10
@sldo_ru

try something like this

User.updateOne({
  { _id: 1 },
  { $pull: { items: { _id: '24123123dsfasdf32' } } }
})

or so, if the first refuses to work
User.updateOne({
  { _id: 1 },
  { $pull: { items: { _id: { $eq: '24123123dsfasdf32' } } }
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question