考虑这两个文档:
{ currentIndex: 1, elements: [4, 5, 6] }
{ currentIndex: 2, elements: [4, 5, 6] }
我如何获得这个结果,按索引 currentIndex
处的 elements
元素排序?
{ currentIndex: 1, elements: [5] }
{ currentIndex: 2, elements: [6] }
我读到了有关 $slice[1] 的内容,但它的参数似乎不能是动态的。所有示例都使用实际整数作为它的参数,而不是标识文档中用作索引的值的字符串。
[1] http://docs.mongodb.org/manual/reference/operator/projection/slice/
最佳答案
如果 currentIndex 是唯一的,或者您可以将唯一字段添加到您的集合中,那么您可以使用 mapreduce:
db.coll.mapReduce(
function() {
emit(this.currentIndex, { currentIndex: this.currentIndex, elementAtCurrentIndex: this.elements[this.currentIndex]});
}, function(key, values) {
return values[0];
}, {
out: "result"
}
)
db.result.find({}, {"value.currentIndex":1, "value.elementAtCurrentIndex":1, _id:0}).sort({"value.elementAtCurrentIndex":1})
关于mongodb - 如何使用文档字段值作为 $slice 的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30791397/