如何在使用 MongoDB 聚合框架展开数组后投影数组索引 [英] How to project array index after unwinding an array with MongoDB aggregation framework

查看:20
本文介绍了如何在使用 MongoDB 聚合框架展开数组后投影数组索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

展开数组时是否可以访问数组索引(http://docs.mongodb.org/manual/reference/operator/aggregation/unwind/#pipe._S_unwind) 使用 MongoDB 聚合管道?

Is it possible to access the array index when unwinding an array (http://docs.mongodb.org/manual/reference/operator/aggregation/unwind/#pipe._S_unwind) using the MongoDB aggregation pipeline?

例如,假设我在集合c"中展开此文档:

For example, suppose I'm unwinding this document in collection "c":

{_id: 1, elements: ["a", "b", "c"]}

那么这个操作:

db.c.aggregate([
 {$unwind: "$elements"}
])

将为文档返回一个光标:

will return a cursor for documents:

[
 {_id: 1, elements: "a"},
 {_id: 1, elements: "b"},
 {_id: 1, elements: "c"}
]

我希望能够在展开之前找出原始数组中a"的索引为 0,b"的索引为 1,而c"的索引为2".

I'd like to be able to figure out aftewards that "a" had index 0, "b" had index 1 and "c" had index "2" in the original array before unwinding.

如何在展开操作中投影数组索引?

How can I project the array index in an unwinding operation?

推荐答案

目前这似乎无法使用聚合框架.有一个未解决的未解决问题与其相关:https://jira.mongodb.org/browse/SERVER-4588.

Currently this seems to be not possible using the aggregation framework. There is an unresolved open issue linked to it: https://jira.mongodb.org/browse/SERVER-4588.

作为一种解决方法,您可以使用 Map-reduce,其中 map 函数为每个数组元素分配一个索引.

As a workaround you could use Map-reduce, with the map function assigning an index to each array element.

var map = function(){
    for(var i=0;i<this.elements.length;i++){
    emit({"_id":this._id,"index":i},{"index":i,"value":this.elements[i]});
    }
}

这篇关于如何在使用 MongoDB 聚合框架展开数组后投影数组索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆