Question

So..I'm evaluating Mongodb for managing a bit of my JSON back end. I'm totally new to it and I had one problem that was just messy to do in code, so I thought — heck — let me check out to see if it's time to finally start using Mongo

I have a data structure that is approximately like this:

[
{
    "_id" : ObjectId("526f59ee82f2e293f9833c54"),
    "humans" : [
        {
            "serviceUsers" : [
                {
                    "foo1" : "bar2",
                    "foo2" : "bar3"
                },
                {
                    "foo1" : "baz2",
                    "foo2" : "baz3"
                }
            ]
        }
    ]
}
]

And now I want to remove any serviceUsers array elements that have "foo1" equal to "baz2" so that ideally I would end up with this:

[
{
    "_id" : ObjectId("526f59ee82f2e293f9833c54"),
    "humans" : [
        {
            "serviceUsers" : [
                {
                    "foo1" : "bar2",
                    "foo2" : "bar3"
                },
            ]
        }
    ]
}
]

I figured that $pull was the place to start. And I tried a bunch of contortions. If I'm in collection mytests, I tried

db.mytests.update({"humans.serviceUsers.foo1":"baz2"}, {$pull:{"humans.serviceUsers" : {"foo1":"baz2"}}}, {multi: true})

Which to my admittedly naive eye, seems like it should follow the $pull syntax:

db.collection.update( { field: <query> }, { $pull: { field: <query> } } );

Mongo doesn't complain. But it doesn't change the collection in any way, either.

I also tried

db.mytests.update({}, {$pull:{"humans.serviceUsers" : {"foo1":"baz2"}}}, {multi: true})

Which also failed.

Any suggestions are greatly appreciated.

Was it helpful?

Solution

Thus humans is also array, you should use positional $ operator to access serviceUsers array of matched humans element:

db.mytests.update({ "humans.serviceUsers.foo1" : "baz2" },
                  { $pull: { "humans.$.serviceUsers" : { "foo1": "baz2" }}});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top