Alex Polkhovsky
Alex Polkhovsky

Reputation: 3360

Remove entry in an array of a MongoDB document

Say I have a document that looks something like this:

{
  "_id": ObjectId("50b6a7416cb035b629000001"),
  "businesses": [{
    "name": "Biz1",
    "id": ObjectId("50b6bc953e47dc923e000001")
  }, {
    "name": "Biz2",
    "id": ObjectId("50b6ccebae0513bf52000001")
  }, {
    "name": "Biz3",
    "id": ObjectId("50b6d015c58b414156000001")
  }, {
    "name": "Biz4",
    "id": ObjectId("50b6d0c8a4cdd5e356000001")
  }]
}

I want to remove

{
        "name": "Biz3",
        "id": ObjectId("50b6d015c58b414156000001")
      }

from the array of businesses. I tried this (using business name instead of id for clarity):

db.users.update({'businesses.name':'Biz3'},{$pull:{'businesses.name':'Biz3'}})

but of course it didn't work. I know that the query part is correct because I get the document back when I do this:

db.users.find({'businesses.name' : 'Biz3'})

So the problem is with the update part.

Upvotes: 0

Views: 134

Answers (1)

IamAlexAlright
IamAlexAlright

Reputation: 1500

Just ran a quick lil test and this works

I think trying db.users.update({'businesses.name':'Biz3'},{$pull:{'businesses':{'name':'Biz3'}}}) should do it

Upvotes: 2

Related Questions