Delete item from 2nd level embedded document

80 views Asked by At

I have a collection of users, which have locations, which have some api keys.

{
    "_id" : ObjectId("5864d5e2962d747913577cc1"),
    "username" : "george",
    "usernameCanonical" : "george",
    "email" : "[email protected]",
    "emailCanonical" : "[email protected]",
    "enabled" : true,
    "password" : "bla bala bla",
    "roles" : [],
    "lastLogin" : ISODate("2016-12-29T09:23:18.000Z"),
    "locations" : [ 
        {
            "_id" : ObjectId("5864da9c962d7476037076b2"),
            "name" : "lalala",
            "address" : "bla bla bla",
            "api_keys" : [ 
                {
                    "_id" : ObjectId("58651d06962d74760b196a52"),
                    "key" : "some valid key1",
                    "is_test" : true
                }
            ]
        }
    ]
}

I am trying to delete an api_key without success.

I tried:

1)

db.getCollection('user').update(
    { 'locations.api_keys._id': ObjectId('5864d5e2962d747913577cc1') },
    {
        $pull: {
            '$.api_keys': {
                 _id: ObjectId("58651d06962d74760b196a52")
            }
        }
    }, false, true
) 

=> Updated 0 record(s) in 7ms

2)

db.getCollection('user').update(
    {},
    {
        $pull: {
            '$.api_keys': {
                _id: ObjectId("58651d06962d74760b196a52")
            }
        }
    }, false, true
) 

=> Updated 1 existing record(s) in 7ms but no changes to the stored object

3

There are 3 answers

0
pankaj007 On BEST ANSWER

Try this

db.getCollection('user').update(
{},
{
    $pull: {
        'locations.0.api_keys': {
            _id: ObjectId("58651d06962d74760b196a52")
        }
    }
}, false, true);
1
Rahul Kumar On

More of a hunch

db.getCollection('user').update(
    {},
    {
        $pull: {
            'locations.$.api_keys': {
                _id: ObjectId("58651d06962d74760b196a52")
            }
        }
    }, false, true
)
1
Rubin Porwal On

According to above mentioned description please try executing following update operation on MongoDB collection

db.user.update(
    {},
    $pull:{locations:{api_keys:
        {$elemMatch:{_id:ObjectId("58651d06962d74760b196a52")}} }}},false,true
    )