0

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

{
    "_id" : ObjectId("5864d5e2962d747913577cc1"),
    "username" : "george",
    "usernameCanonical" : "george",
    "email" : "george.something@gmail.com",
    "emailCanonical" : "george.something@gmail.com",
    "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

chridam
  • 100,957
  • 23
  • 236
  • 235

3 Answers3

2

Try this

db.getCollection('user').update(
{},
{
    $pull: {
        'locations.0.api_keys': {
            _id: ObjectId("58651d06962d74760b196a52")
        }
    }
}, false, true);
pankaj007
  • 95
  • 7
0

More of a hunch

db.getCollection('user').update(
    {},
    {
        $pull: {
            'locations.$.api_keys': {
                _id: ObjectId("58651d06962d74760b196a52")
            }
        }
    }, false, true
)
Rahul Kumar
  • 2,781
  • 1
  • 21
  • 29
  • sorry, it throws an error. `The positional operator did not find the match needed from the query. Unexpanded update: locations.$.api_keys` – George Ploscaru Dec 30 '16 at 21:17
0

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
    )
Rubin Porwal
  • 3,736
  • 1
  • 23
  • 26