2015-02-05 86 views
1
{ 
    "_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 
    ] 
} 

我想从bidPrices中获得哪些索引是“1,3,5,6”的价格。 我只知道使用$ slice,mongo会返回bidPrices的子数组。 有没有什么办法让蒙戈回报这样的数组:如何在MongoDb中按特定索引获取元素

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

谢谢!

+0

为什么你想回到这个集合的元素?你不能只修剪你的客户端代码吗?如果这是你需要在许多文档上经常做的事情,那么你应该重新设计你的模式来处理它。 (2.6)MongoDB不支持这样的投影。 – wdberkeley 2015-02-05 18:55:46

回答

0

使用的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" 
        } 
        ) 
+0

好的,我会试试看。但我担心效率。有没有人可以告诉我这件事? – 2015-02-06 03:43:42

+0

它应该是相当有效的在你的情况。 – 2015-02-07 12:08:19