MongoDB展开多个数组 [英] MongoDB unwind multiple arrays
本文介绍了MongoDB展开多个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在mongodb中,文档具有以下结构:
{
"_id" : ObjectId("52d017d4b60fb046cdaf4851"),
"dates" : [
1399518702000,
1399126333000,
1399209192000,
1399027545000
],
"dress_number" : "4",
"name" : "J. Evans",
"numbers" : [
"5982",
"5983",
"5984",
"5985"
]
}
是否可以从多个数组展开数据并从数组中仅获取配对的元素:
{
"dates": "1399518702000",
"numbers": "5982"
},
{
"dates": "1399126333000",
"numbers": "5983"
},
{
"dates": "1399209192000",
"numbers": "5984"
},
{
"dates": "1399027545000",
"numbers": "5985"
}
解决方案
从3.2版开始,您可以在两个数组上都使用$unwind
,在$cmp
上使用索引,而在$match
上使用相同的索引. /p>
在只有示例文档的情况下,此解决方案将填充您编写的内容.如果您有更多文档,我不知道您期望在输出中得到什么,但是可以通过按文档的_id分组来解决.
db.test.aggregate([
{
$unwind: {
path: '$dates',
includeArrayIndex: 'dates_index',
}
},
{
$unwind: {
path: '$numbers',
includeArrayIndex: 'numbers_index',
}
},
{
$project: {
dates: 1,
numbers: 1,
compare: {
$cmp: ['$dates_index', '$numbers_index']
}
}
},
{
$match: {
compare: 0
}
},
{
$project: {
_id: 0,
dates: 1,
numbers: 1
}
}
])
In mongodb there are documents in the following structure:
{
"_id" : ObjectId("52d017d4b60fb046cdaf4851"),
"dates" : [
1399518702000,
1399126333000,
1399209192000,
1399027545000
],
"dress_number" : "4",
"name" : "J. Evans",
"numbers" : [
"5982",
"5983",
"5984",
"5985"
]
}
Is it possible unwind data from multiple arrays and get only paired elements from arrays:
{
"dates": "1399518702000",
"numbers": "5982"
},
{
"dates": "1399126333000",
"numbers": "5983"
},
{
"dates": "1399209192000",
"numbers": "5984"
},
{
"dates": "1399027545000",
"numbers": "5985"
}
解决方案
From version 3.2 you can do it with $unwind
on both of the arrays, $cmp
the indexes, and $match
only the equal indexes.
This solution will populate what you wrote in case you have only the example document. If you have more documents I don't know what you expect to get in the output, but it's solvable by grouping by _id of the document.
db.test.aggregate([
{
$unwind: {
path: '$dates',
includeArrayIndex: 'dates_index',
}
},
{
$unwind: {
path: '$numbers',
includeArrayIndex: 'numbers_index',
}
},
{
$project: {
dates: 1,
numbers: 1,
compare: {
$cmp: ['$dates_index', '$numbers_index']
}
}
},
{
$match: {
compare: 0
}
},
{
$project: {
_id: 0,
dates: 1,
numbers: 1
}
}
])
这篇关于MongoDB展开多个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文