通过索引从文档字段中选择自定义数组元素
问题描述:
我可以通过文档中定义的索引选择特定的数组元素吗?通过索引从文档字段中选择自定义数组元素
例如,我有以下文件:
{ "_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
操作?
答
的最佳方式做,这是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 ] } ]