-1

这是我的桌子

unicorns =  {'name':'George',
             'actions':[{'action':'jump', 'time':123123}, 
                        {'action':'run', 'time':345345}, 
                        ...]}

如何执行以下查询?

  • 抓取所有独角兽所有动作的时间,其中action=='jump'

  • 抓住时间相等的所有独角兽的所有动作?

    例如 {'action':'jump', 'time':123} 和 {'action':'stomp', 'time':123}


帮助将是惊人的=)

4

2 回答 2

2

使用点分隔符号:

db.unicorns.find({'actions.action' : 'jump'})

同样的时间:

db.unicorns.find({'actions.time' : 123})

编辑:如果要按时间对结果进行分组,则必须使用MapReduce

于 2010-07-25T23:49:49.360 回答
2

对于第二个查询,您需要使用 MapReduce,这可能会让人毛骨悚然。这将起作用:

map = function() {
    for (var i = 0, j = this.actions.length; i < j; i++) {
        emit(this.actions[i].time, this.actions[i].action);
    }
}
reduce = function(key, value_array) {
    var array = [];
    for (var i = 0, j = value_array.length; i < j; i++) {
        if (value_array[i]['actions']) {
            array = array.concat(value_array[i]['actions']);
        } else {
            array.push(value_array[i]);
        }
    }
    return ({ actions: array });
}

res = db.test.mapReduce(map, reduce)
db[res.result].find()

这将返回类似这样的内容,其中_id键是您的时间戳:

{ "_id" : 123, "value" : { "actions" : [ "jump" ] } }
{ "_id" : 125, "value" : { "actions" : [ "neigh", "canter" ] } }
{ "_id" : 127, "value" : { "actions" : [ "whinny" ] } }

不幸的是,mongo 目前不支持从 reduce 函数返回数组,因此需要使用愚蠢的{actions: [...]}语法。

于 2010-07-26T20:15:15.170 回答