ruby – 如何在MongoDB映射函数中对BSON对象进行字符串化?
发布时间:2020-12-17 03:34:43 所属栏目:百科 来源:网络整理
导读:我有包含字段xyz的文档 { term: "puppies",page: { skip: 1,per_page: 20 } } // not useful as a composite key...{ page: { skip: 1,per_page: 20 },term: "puppies" } // different order,same contents 为了确定xyz中的“顶部”值,我想将它们全部映射到
我有包含字段xyz的文档
{ term: "puppies",page: { skip: 1,per_page: 20 } } // not useful as a composite key... { page: { skip: 1,per_page: 20 },term: "puppies" } // different order,same contents 为了确定xyz中的“顶部”值,我想将它们全部映射到类似的东西 emit('term="puppies",page={ skip: 1,per_page: 20 }',1); // composite key 但是我无法将嵌入的对象变成有意义的字符串: emit('term="puppies",page=[object bson_object]',1); // not useful 有关使用函数而不是toString()的任何建议吗? # return the top <num> values of <field> based on a query <selector> # # example: top(10,:xyz,{},{}) def top(num,field,selector,opts = {}) m = ::BSON::Code.new <<-EOS function() { var keys = []; for (var key in this.#{field}) { keys.push(key); } keys.sort (); var sortedKeyValuePairs = []; for (i in keys) { var key = keys[i]; var value = this.#{field}[key]; if (value.constructor.name == 'String') { var stringifiedValue = value; } else if (value.constructor.name == 'bson_object') { // this just says "[object bson_object]" which is not useful var stringifiedValue = value.toString(); } else { var stringifiedValue = value.toString(); } sortedKeyValuePairs.push([key,stringifiedValue].join('=')); } // hopefully we'll end up with something like // emit("term=puppies,page={skip:1,per_page:20}") // instead of // emit("term=puppies,page=[object bson_object]") emit(sortedKeyValuePairs.join(','),1); } EOS r = ::BSON::Code.new <<-EOS function(k,vals) { var sum=0; for (var i in vals) sum += vals[i]; return sum; } EOS docs = [] collection.map_reduce(m,r,opts.merge(:query => selector)).find({},:limit => num,:sort => [['value',::Mongo::DESCENDING]]).each do |doc| docs.push doc end docs end 解决方法
鉴于
MongoDB uses SpiderMonkey as its internal JS engine,你不能使用
JSON.stringify (即使/当MongoDB
switches to V8时也能工作)或SpiderMonkey的非标准
toSource method?
(对不起,不能尝试ATM确认它的工作) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |