i have document in format:
{_id:objectid("541...009b"), name:"abc" data:{"f_001":123abc, "priority":"urgent", ...},... }
wanted write common function update key {data.f_001:0}, otherwise data remain is:
updateexistingkey("user", {name:"abc"}, "data.f_001");
as wasn't able achieve goal, i've tried print value, without success:
function updateexistingkey(collection, query, keyname){ db[collection].find(query).foreach(function(document) { print(document._id) // prints objectid("541...009b") print(keyname) // prints "data.f_001" print(document.data.f_001) // prints 123abc print(document[keyname]); // prints undefined rather 123abc, why?? }); }
print(document.data.f_001) // prints 123abc print(document[keyname]); // prints undefined rather 123abc, why?? ^^^
embedded documents really embedded (i.e.: nested). not flat data structure fields having dot in them. so, dot notation might seen path allowing access field embedded in nested objects. said, both equivalent:
document.data.f_001 document["data"]["f_001"]
but is not same as
document["data.f_001"]
if want update 1 arbitrary field key name, function prototype match mongodb update
function (with notable exception value missing. assume here hard coded). simple wrapper need. like that:
function updateexistingkey(collection, query, keyname){ updt = {}; updt[keyname] = "somenewvalue"; db[collection].update(query, {$set: updt}, {multi: true}); }
untested: beware of typos !
if want retrieve 1 arbitrary field, might use $project
operator of aggregation framework map arbitrary field name known field in output document:
function printexistingkey(collection, query, keyname){ // xxx need "keyname" validation here // ... db[collection].aggregate([ {$match: query }, {$project: { datafield: "$" + keyname }} ]).foreach(function(d) { print(d._id); print(d.datafield); }); }
untested: beware of typos !
Comments
Post a Comment