0

I need to remove entries inside a 2d array of documents structure in mongodb.

Sample is as below

{
    "_id" : ObjectId("5ffef283f1f06ff8524aa2c2"),
    "applicationName" : "TestApp",
    "pName" : "",
    "environments" : [],
    "stages" : [],
    "createdAt" : ISODate("2021-01-15T09:51:35.546Z"),
    "workflows" : [ 
        [ 
            {
                "pName" : "Test1",
                "wName" : "TestApp_Test1",
                "agent" : ""
            }, 
            {
                "pName" : "Test2",
                "wName" : "TestApp_Test2",
                "agent" : ""
            }
        ], 
        [ 
            {
                "pName" : "Test1",
                "wName" : "TestApp_Test1",
                "agent" : ""
            }
        ]
    ],
    "updatedAt" : Date(-62135596800000)
}

So, I want to remove all document occurences of

{
  "pName" : "Test1",
  "wName" : "TestApp_Test1",
  "agent" : ""
}

from both the arrays.

pName:Test1 can be used to filter it out.

What's the query which can be used to find this and delete it ?

I am ok to do a find and then iterate over the collection , find the matching entry and then update the document. I have to do this using Go mongodb driver

Since this is kind of complex for me as I am new to both golang and mongo db, I am stuck.

Update: 1.Tried {$pull: {workflows: {pName:"Test1"}}}, {multi: true} in the update() call as suggested but didn't work.

2.Tried something like this

db.getCollection('workflows').update({_id:ObjectId('5ffef283f1f06ff8524aa2c2')}, {$pull:{workflows: { $elemMatch: {pName:'Test2'}}}} )

This is removing the entire array as shown below because Test2 is present in that. I need to remove only the Test2 document

[ 
    {
        "pName" : "Test1",
        "wName" : "TestApp_Test1",
        "agent" : ""
    }, 
    {
        "pName" : "Test2",
        "wName" : "TestApp_Test2",
        "agent" : ""
    }
]
0

1 Answer 1

1

I'll give you a hint as you are new and you haven't posted the tried things.

You could use $pull to remove documents matching the conditions.

similar example

And you could use official mongodb driver for go or most used gopkg

An example SO post

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I tried {$pull: {workflows: {pName:"Test1"}}}, {multi: true} in the update() call. It said it updated in the mongo client but it didn't remove the entry. I know this needs a modification since its another enclosing array. How do we do it in this case ?
Alternatively, you can iterate by simple find and update workflows after removing programmatically.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.