Search code examples
mongodbbsonmongo-c-driver

nesting $pull commands in Mongo


I am attempting to remove a value from multiple arrays without having to issue multiple Mongo commands. I must have my syntax incorrect, any help would be appreciated.

When I try:

update = BCON_NEW("$pull", 
        "{", 
            "files.$.like", BCON_UTF8 (account_id), 
        "}",
        "{", 
            "files.$.hate", BCON_UTF8 (account_id), 
        "}",
        "{", 
            "files.$.love", BCON_UTF8 (account_id), 
        "}",
        "{", 
            "files.$.funny", BCON_UTF8 (account_id), 
        "}",
        "{", 
            "files.$.sad", BCON_UTF8 (account_id), 
        "}",
        "{", 
            "files.$.anger", BCON_UTF8 (account_id), 
        "}",
        "{", 
            "files.$.kiss", BCON_UTF8 (account_id), 
        "}"
        );

It fails if I simplify it down to just the following it works:

update = BCON_NEW("$pull", 
        "{", 
            "files.$.like", BCON_UTF8 (account_id), 
        "}"
        );

Solution

  • The $pull operates on the document that follows it. See MongoDB Documentation on $pull. I'd never seen the BCON notation before now, so I might be wrong, but if I'm understanding it correctly, I believe that the document created by your code would look like this:

    {
        $pull: { "files.$.like": BCON_UTF8 (account_id) } //Here's the end of your $pull document,
        { "files.$.hate": BCON_UTF8 (account_id) },
        { "files.$.love": BCON_UTF8 (account_id) },
        ...
    }, 
    

    Instead, I think you want something that looks like this (I have not tested this):

    update = BCON_NEW("$pull", 
        "{", 
            "files.$.like", BCON_UTF8 (account_id),  
            "files.$.hate", BCON_UTF8 (account_id), 
            "files.$.love", BCON_UTF8 (account_id), 
            "files.$.funny", BCON_UTF8 (account_id), 
            "files.$.sad", BCON_UTF8 (account_id), 
            "files.$.anger", BCON_UTF8 (account_id), 
            "files.$.kiss", BCON_UTF8 (account_id), 
        "}"
        );