2015-07-20 65 views
1

我可以通过文档中定义的索引选择特定的数组元素吗?通过索引从文档字段中选择自定义数组元素

例如,我有以下文件:

{ "_id" : 1, "idx" : 1, "vals" : [ 1, 2 ] } 

,我想选择由idx指数定义vals元素。

我已成功地选择由字面定义的特定数组元素:

> db.test.find({_id:1}, {vals:{$slice:[1, 1]}}) 
{ "_id" : 1, "idx" : 1, "vals" : [ 2 ] } 

但我怎么能使用idx$slice操作?

回答

1

的最佳方式做,这是MongoDB的3.2使用$arrayElemAt操作:

db.test.aggregate([ 
    { "$project": { "vals": { "$arrayElemAt": [ "$vals", "$idx" ] } } } 
]) 

您也可以使用findOne,如果你在你的查询条件使用_id并得到idx值。

var idx = db.test.findOne({ "_id": 1 }).idx 
db.test.find({ "_id": 1 }, { "vals": { "$slice": [ idx, 1 ]}}) 

随着find你需要使用cursor.map

db.test.find().map(function(doc) { 
    doc.vals = doc.vals.slice(doc.idx, 2); 
    return doc; 
}) 

结果:

[ { "_id" : 1, "asd" : 1, "vals" : [ 2 ] } ]