在使用MongoDB聚合管道展开数组(http://docs.mongodb.org/manual/reference/operator/aggregation/unwind/#pipe._S_unwind)时是否可以访问数组索引?
例如,假设我在集合"c"中展开此文档:
{_id: 1, elements: ["a", "b", "c"]}
那么这个操作:
db.c.aggregate([
{$unwind: "$elements"}
])
将返回文档的游标:
[
{_id: 1, elements: "a"},
{_id: 1, elements: "b"},
{_id: 1, elements: "c"}
]
我希望能够在展开之前弄清楚原始数组中的"a"有索引 0,"b"有索引 1,"c"有索引"2"。
如何在展开操作中投影数组索引?
新发布的MongoDB 3.2支持数组索引的展开。
您可以传递一个包含字段path
的对象以及将保存数组索引的字段includeArrayIndex
,而不是通过 $unwind
运算符传递路径。
来自MongoDB官方文档:
{
$unwind:
{
path: <field path>,
includeArrayIndex: <string>,
preserveNullAndEmptyArrays: <boolean>
}
}
使用聚合框架似乎无法做到这一点。有一个未解决的未解决的问题链接到它:https://jira.mongodb.org/browse/SERVER-4588。
作为一种解决方法,您可以使用 Map-reduce,让 map 函数为每个数组元素分配一个索引。
var map = function(){
for(var i=0;i<this.elements.length;i++){
emit({"_id":this._id,"index":i},{"index":i,"value":this.elements[i]});
}
}