3

I have managed to do better things with C Driver, but stuck on this simple point:

How do I search by a known Id? Among many things, this is what I have tried that seemed most logical:

query = BCON_NEW (
       "some_field", BCON_INT32(4),
       "_id", "{", 
           "$oid", "5414096132e0353007000017",
        "}"
    );

Query works fine if I do not include _id field. With _id, returns nothing, and no errors. Of course, a record with that _id exists in db.

On the same topic, I have had difficulties forming an array of Ids for $in query. Hopefully this will help there too.

bson_t shiftIds;
BSON_APPEND_UTF8 (&shiftIds, "$oid", key); //Key is the shiftId string value, this goes in loop
query = BCON_NEW (
          "some_field", BCON_INT32(4),
          "shiftId", "{", 
            "$in", BCON_ARRAY(&shiftIds),
          "}"
     );

In this part, something goes wrong with appending $oid in BSON_APEND_UTF8 method. Program terminates on reaching there.

Any help is appreciated!

trappedIntoCode
  • 804
  • 8
  • 13

2 Answers2

3

if you want to find by _id, maybe you can do it like this:

bson_oid_t oid;
bson_oid_init_from_string (&oid, "5414096132e0353007000017");
query = BCON_NEW ("_id", BCON_OID(&oid));
Faruk
  • 5,438
  • 3
  • 30
  • 46
1

Alternative solution to your first question:

bson_init_from_json(query, "{\"_id\":{\"$oid\":\"5414096132e0353007000017\"}}", -1, NULL);

Solution to your second question: mongo c driver: how to query documents with "_id" in a list?

Johnson
  • 121
  • 10