Reputation: 30933
i have document that looks like this :
{
"_id" : ObjectId("5768e43"),
"APPID" : {
"Number" : 0,
},
sessions : [{
id : 111111,
"setOID" : {
"Number" : 0
},
"custID" : {
"Number" : 0
},
}, {
id : 133333,
"setOID" : {
"Number" : 2
},
"custID" : {
"Number" : 2
},
}, {
id : 7777,
"setOID" : {
"Number" : 2
},
"custID" : {
"Number" : 2
},
},
]
}
I like to get the sessions elment which its id == 133333 ( which is in [1] ) and be able to update it with new values and add new elements to it so it will look like this :
{
id : 133333,
"setOID" : {
"Number" : 3333
},
"custID" : {
"Number" : 4444
},
new_attr_1 : 0
new_attr_2 : 2
},
The documentation is very hard to understand when it comes to C Driver can someone please show what it the best way to do it ?
UPDATE
I tried with cdriver version 1.4 ( latest ) and weird thing is happening
the update did failed ( returend true )
but there is no update in the document
bson_t *query2 = BCON_NEW ("sessions.id ", BCON_INT32 (133333));
bson_t *update;
update = BCON_NEW ("$set", "{","Sessions.$.new_attr_1" ,BCON_INT32 (0) ,"}");
if (!mongoc_collection_update (collection,MONGOC_UPDATE_NONE, query2, update, NULL, &error)) {
fprintf (stderr, "%s\n", error.message);
goto fail;
}
so as you see allot of strange things happening , how can i check if update is really successful ?
Upvotes: 2
Views: 213
Reputation: 73
To answer your question here is a solution :
db.doc.update({"sessions.id":133333},
{$set: {"sessions.$.setOID.Number":3333,
"sessions.$.custID.Number":4444,
"sessions.$.new_attr_1" : 0,
"sessions.$.new_attr_2" : 2
}
})
And with the C Drive should be something like that :
static void updateSession( mongo_connection *conn ) {
bson cond[1], op[1];
bson_init( cond );
bson_append_int( cond, "sessions.id",133333);
bson_finish( cond );
bson_init( op );
bson_append_start_object( op, "$set" );
bson_append_int( op, "sessions.$.setOID.Number",3333);
bson_append_int( op, "sessions.$.custID.Number",4444);
bson_append_int( op, "sessions.$.new_attr_1",0);
bson_append_int( op, "sessions.$.new_attr_2",2);
bson_append_finish_object( op );
bson_finish( op );
mongo_update( conn, "db.doc", cond, op, MONGO_UPDATE_BASIC );
bson_destroy( cond );
bson_destroy( op );
}
Upvotes: 1