Search code examples
mongodbbsonmongo-c-driver

mongo c-driver bcon $ne value no equal


I am trying to append a requirement to my BCON query where 'tribe_type' does not equal 'initial-public'.

My original code was and that worked:

 query = BCON_NEW ("_id", BCON_OID(&oid));

When I add the second part, it compiles, however the mongo match fails.

        query = BCON_NEW ("_id", BCON_OID(&oid),
            "{",
                "tribe_type",
                "$ne",
                "initial-public",
            "}"
        );

Solution

  • You have to specify the BCON type for UTF-8 strings.
    Be careful with implict $and's Be careful with nested documents and BCON.

        query = BCON_NEW ("_id", BCON_OID(&oid),
            "{",
                "tribe_type",
                "$ne",
                "initial-public",
            "}"
        );
    

    compiles into this command

     { "_id" : <an oid> }, { "tribe_type" : "$ne" }
    

    which is obviously not what you want.

    be explicit with the $and operation, correctly type the string as a UTF8 field, and make sure you capture the nested documents like this:

    query = BCON_NEW (
                    "$and", "[", "{", "_id", BCON_OID(&oid), "}",
                                 "{", "tribe_type", "{", "$ne", BCON_UTF8 ("initial-public"), "}", "}","]"
                    );
    

    yields a query that looks like this

    { "$and" : [ { "_id" : <an oid> }, { "tribe_type" : { "$ne" : "initial-public" } } ] }
    

    which is probably what you want.