select 根据文档字段的索引自定义数组元素

select custom array element by index from document field

我可以 select 文档中定义的特定数组元素吗?

例如我有以下文档:

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

我想 select valsidx 索引定义的元素。

我已经设法 select 由文字定义的特定数组元素:

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

但是如何在 $slice 运算符中使用 idx 字段?

执行此操作的最佳方法是在 MongoDB 3.2 中使用 $arrayElemAt 运算符:

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

如果您在查询条件中使用 _id 并获得 idx 值,您也可以使用 findOne

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 ] } ]