我有字段 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 上试用以确认它是否有效)
关于ruby - 如何在 MongoDB 映射函数中对 BSON 对象进行字符串化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5723889/