我正在使用Mongodb,但我可以迁移到mysql,我的问题是,我有一个包含这样的数据的集合,
array(
"L"=>"cars",
"M"=>"wolkswagen"
)
array(
"L"=>"cars",
"M"=>"bmw"
)
array(
"L"=>"cars",
"M"=>"mercedes"
)
array(
"L"=>"bike",
"M"=>"bianchi"
)
array(
"L"=>"bike",
"M"=>"trek"
)
array(
"L"=>"bike",
"M"=>"brook"
)
我想得到的结果是,任何自行车和汽车,但每个都有2个结果,所以结果应该是,
array(
"L"=>"cars",
"M"=>"some car"
)
array(
"L"=>"cars",
"M"=>"some car"
)
array(
"L"=>"bike",
"M"=>"some bike"
)
array(
"L"=>"bike",
"M"=>"some bike"
)
我尝试用$ in做这个,但似乎没有用,有什么想法吗?
答案 0 :(得分:1)
使用MongoDB 2.2 +中的Aggregation Framework可以通过几种方法解决此问题。
不幸的是,2.2.2版的聚合框架还不支持$slice
或数组子集运算符,因此需要一些额外的操作。
注意:下面的示例使用mongo
shell,但应该直接转换为PHP驱动程序。
假设您没有考虑为每个分组获得哪两个元素,您可以选择$first
和$last
:
db.cars.aggregate(
// Group by $L and find the first and last elements
{ $group: {
_id: '$L',
first: { $first: "$M" },
last: { $last: "$M" },
}},
// Add an extra $index for # of array elements
{ $project: {
first: 1,
last: 1,
index: { $const:[0,1] }
}},
// Split into document stream based on $index
{ $unwind: '$index' },
// Re-group data using conditional to create array
{ $group: {
_id: '$_id',
M: {
$push: { $cond:[ {$eq:['$index', 0]}, '$first', '$last'] }
}
}}
)
示例输出:
{
"result" : [
{
"_id" : "cars",
"M" : [
"wolkswagen",
"mercedes"
]
},
{
"_id" : "bike",
"M" : [
"bianchi",
"brook"
]
}
],
"ok" : 1
}
上面的替代方案是使用$addToSet
的更简单的管道以及修剪数组元素的后处理步骤:
var agg = db.cars.aggregate(
{ $group: {
_id: '$L',
'M': { $addToSet: "$M" },
}}
)
// Iterate to trim each result to the desired # of elements
agg.result.forEach(function(doc) {
// Note: you could randomly select 2 (or n) elements here
doc.M = doc.M.slice(0,2);
})
输出格式与示例#1相同,但不是选择第一个&最后一个元素,例如#2(如所写)选择前两个元素。