开发者

Various queries - MongoDB

This is my table:

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

How can I perform the following queries?

  • Grab the开发者_StackOverflow time of all actions of all unicorns where action=='jump' ?

  • Grab all actions of all unicorns where time is equal?

    e.g. {'action':'jump', 'time':123} and {'action':'stomp', 'time':123}


Help would be amazing =)


For the second query, you need to use MapReduce, which can get a big hairy. This will work:

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()

This would return something like this, where the _id keys are your timestamps:

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

Unfortunately, mongo doesn't currently support returning an array from a reduce function, thus necessitating the silly {actions: [...]} syntax.


Use dot-separated notation:

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

Similarly for times:

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

Edit: if you want to group the results by time, you'll have to use MapReduce.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜