LUKER
LUKER

Reputation: 536

Pull Document By ID from Triple Nested Array MongoDB

I'd like to be able to pull a document by id from a triple nested array of documents. DB looks something like this:

[{
    type: "Foods",
    fruit: [{
      name: "Apple",
      kinds: [{
        name: "Red Delicious"
        details: [{
           _id: ObjectId("123123123"),
           colors: ["red", "yellow"]
           }]
        }]
    }]
}]

I'd like to be able to pull the document with the _id: 123123123. I've tried many different ways, but it always says it matches, but won't modify the document.

I've tried:

db.stuff.update({}, {$pull: {fruits: {kinds: {details: {_id: "123123123"}}}}}), 
db.stuff.update({}, {$pull: {"fruits.kinds.details' : {_id: "123123123"}}}),
db.stuff.update({}, {$pull: {"fruits.$[].kinds.$[].details' : {_id: "123123123"}}})  

But everytime it matches, but won't delete the document. Please help.

Upvotes: 1

Views: 256

Answers (1)

mickl
mickl

Reputation: 49945

The last attempt is correct however you need to fix two things: fruit instead of fruit (according to your sample data) and types needs to match so you have to convert string to ObjectId

db.stuff.update({}, {$pull: {"fruit.$[].kinds.$[].details' : {_id: mongoose.Types.ObjectId("123123123")}}}) 

Upvotes: 1

Related Questions