简体   繁体   中英

How to get element by specific index in MongoDb

{
  "_id": newDate("2/5/2015 15:00:18"),
  "bidPrices": [
    13.78,
    13.77,
    13.76,
    13.75,
    13.74,
    13.73,
    13.72,
    13.71,
    13.7,
    13.69
  ],
  "askPrices": [
    13.79,
    13.8,
    13.81,
    13.82,
    13.83,
    13.84,
    13.85,
    13.86,
    13.87,
    13.88
  ]
}

I wanna get prices from bidPrices which indexes are "1,3,5,6" . All i know is use $slice , mongo will return a sub array of bidPrices. Is there any way to make the mongo return such array:

[0, 13.77, 0, 13.75, 0, 13.73, 13.72, 0, 0, 0] 

Thanks!

Using Map Reduce

var mapFunction = function(){
                                for (var i in this.bidPrices) {
                                    if(i == 1 || i == 3 || i == 5 || i == 6){
                                        emit(this._id, this.bidPrices[i]);
                                    }
                                }; 
                            };

var reduceFunction = function(key, values) {
                            var reduced = {};     
                                for (var i in values) {
                                        reduced[i] = values[i];
                                };
                            return reduced;            
                };

db.test2.mapReduce(
                     mapFunction,
                     reduceFunction,
                     { out: "test2_res"
                     }
                   )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM