I am running into a problem and I am not sure how to fix it. Any help you can provide would be great, I am sure it is something stupid I am doing wrong. :)
I am trying to $push some items into an array titled "subscribed_tribes". Here is my document prior to any pushes:
{
"_id" : ObjectId("5693fc1f6890f14daa0e26e1"),
"password" : "7CAE......",
"salt" : "748D...",
"created" : ISODate("2016-01-11T19:01:51.000+0000"),
"display_name" : "2686....",
"my_tribes" : "",
"subscribed_tribes" : ""
}
When I run the following c code nothing happens (no changes).
collection = mongoc_client_get_collection (client, "STribe", "users");
query = bson_new ();
bson_oid_t oid;
char *techSupportID = "5693c0196890f159c1741bb1";
bson_oid_init_from_string (&oid, techSupportID);
query = BCON_NEW ("_id", BCON_OID(&oid));
// Find the document
cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, query, NULL, NULL);
update = bson_new ();
//BSON_APPEND_UTF8 (update, "testing", "blah");
//mongoc_collection_update (collection, MONGOC_UPDATE_NONE, query, update, NULL, &error);
// Assemble query
update = BCON_NEW ("$push",
"{",
"subscribed_tribes",
"{",
"tribe_id", BCON_UTF8 (tribe_id),
"tribe_key", BCON_UTF8 (passphrase),
"}",
"}");
mongoc_collection_update (collection, MONGOC_UPDATE_NONE, query, update, NULL, &error);
If I uncomment the two lines of code (bson_append and mongc_collection_update) then the entire document is overwritten and replaced with:
{
"_id" : ObjectId("5693c0196890f159c1741bb1"),
"testing" : "blah",
"subscribed_tribes" : [
{
"tribe_id" : "5624200d4bacd3940b8b2d62",
"tribe_key" : "27D719EDC7A59...."
}
]
}
Any ideas why the original code doesn't add the array item into subscribed_tribes correctly? Secondly why does the inclusion of the uncommented lines overwrite the entire document?
Once again I am sure I am doing something stupid, but I am just not sure what.
subscribed_tribes
is currently a string, not an array. That's why you can't use $push
on it.
If you inspect the populated error
result, you should be getting an error message about that.
So your doc needs to look like this for $push
to work:
{
"_id" : ObjectId("5693fc1f6890f14daa0e26e1"),
"password" : "7CAE......",
"salt" : "748D...",
"created" : ISODate("2016-01-11T19:01:51.000+0000"),
"display_name" : "2686....",
"my_tribes" : "",
"subscribed_tribes" : []
}