我有一个具有以下结构的数组:
Array
(
[526e379cdc178e5f8fb31e84] => Array
(
[_id] => MongoId Object
(
[$id] => 526e379cdc178e5f8fb31e84
)
[lv] => Array
(
[0] => Array
(
[ln] => Hospital bill review
[pa] => Auditing
)
[1] => Array
(
[ln] => Fraud
[pa] => -1
)
[2] => Array
(
[ln] => Type of detected/predicted fraud
[pa] => Fraud
)
[3] => Array
(
[ln] => Individual fraud
[pa] => Type of detected/predicted fraud
)
)
[pn] => AU2000240683A2
)
[526e379bdc178e5f8fb31e0d] => Array
(
[_id] => MongoId Object
(
[$id] => 526e379bdc178e5f8fb31e0d
)
[lv] => Array
(
[0] => Array
(
[ln] => Claim processing
[pa] => Methods for detecting/predicting fraud
)
[1] => Array
(
[ln] => Claim cost management(settlement)
[pa] => -1
)
[2] => Array
(
[ln] => Multiple payer options/ liability computation
[pa] => Claim cost management(settlement)
)
)
[pn] => AU2001239752B2
)
)
我正在使用以下聚合函数:
$out = $collection->aggregate(array(
array('$unwind'=>'$lv'),
array('$match' => array('lv.pa'=>-1)),
array('$group'=>array(_id=>'$lv.ln')),
)
);
print_r($out);
它给出了以下结果:
Array
(
[result] => Array
(
[0] => Array
(
[_id] => Fraud
)
[1] => Array
(
[_id] => Claim cost management(settlement)
)
)
[ok] => 1
)
但我想要不使用PHP的结构如下所示。我已经使用PHP实现了它。
Array
(
[result] => Array
(
[0] => Fraud
[1] => Claim cost management(settlement)
)
[ok] => 1
)
提前致谢。
答案 0 :(得分:2)
提醒一下,MongoDB的结果是文档的序列/数组。 虽然BSON数组在内部与(子)文档非常相似,但它只能是字段的值。 BSON数组不能作为顶级结果返回。
以下聚合函数
$out = $collection->aggregate(array(
array('$unwind'=>'$lv'),
array('$match' => array('lv.pa'=>-1)),
array('$group'=>array(_id=>'$lv.pa', ln=>array('$addToSet'=>'$lv.ln'))),
array('$project'=>array(_id=>0, ln=>'$ln'))
)
);
print_r($out);
应该有以下结果。
Array
(
[result] => Array
(
[ln] => Array
(
[0] => Fraud
[1] => Claim cost management(settlement)
)
)
[ok] => 1
)
虽然我没有对上述内容进行测试,但我测试了以下等效的JavaScript。
var docs = [
{
'_id': ObjectId("526e379cdc178e5f8fb31e84"),
'lv': [
{
'ln': 'Hospital bill review',
'pa': 'Auditing'
},
{
'ln': 'Fraud',
'pa': -1
},
{
'ln': 'Type of detected / predicted fraud',
'pa': 'Fraud'
},
{
'ln': 'Individual fraud',
'pa': 'Type of detected / predicted fraud'
}
]
},
{
'_id': ObjectId('526e379bdc178e5f8fb31e0d'),
'lv': [
{
'ln': 'Claim processing',
'pa': 'Methods for detecting / predicting fraud'
},
{
'ln': 'Claim cost management(settlement)',
'pa': -1
},
{
'ln': 'Multiple payer options / liability computation',
'pa': 'Claim cost management(settlement)'
}
]
}
];
db.test.remove();
db.test.save(docs);
var pipeline = [
{$unwind: '$lv'},
{$match: {'lv.pa': -1}},
{$group: {_id: '$lv.pa', ln: {$addToSet: '$lv.ln'}}},
{$project: {_id: 0, ln: '$ln'}}
];
printjson(db.test.aggregate(pipeline));
结果如下。
{
"result" : [
{
"ln" : [
"Fraud",
"Claim cost management(settlement)"
]
}
],
"ok" : 1
}
答案 1 :(得分:-1)
尝试删除组
的数组$out = $collection->aggregate(array(
array('$unwind'=>'$lv'),
array('$match' => array('lv.pa'=>-1)),
array('$group'=>{_id=>'$lv.ln'}),
)
);