Sea*_*ere 5 ruby json mongodb bson
我有包含字段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
Run Code Online (Sandbox Code Playgroud)
为了确定xyz中的"顶部"值,我想将它们全部映射到类似的东西
emit('term="puppies",page={ skip: 1, per_page: 20 }', 1); // composite key
Run Code Online (Sandbox Code Playgroud)
但是我无法将嵌入的对象变成有意义的字符串:
emit('term="puppies",page=[object bson_object]', 1); // not useful
Run Code Online (Sandbox Code Playgroud)
有关使用函数的任何建议而不是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
Run Code Online (Sandbox Code Playgroud)
鉴于MongoDB使用SpiderMonkey作为其内部JS引擎,你不能使用JSON.stringify(即使/当MongoDB 切换到V8时)或SpiderMonkey的非标准toSource方法吗?
(对不起,不能尝试ATM确认它的工作)
| 归档时间: |
|
| 查看次数: |
4677 次 |
| 最近记录: |