Mongodb聚合使用文档字段作为数组结果的键而不是增量数字
我的聚合在 mongodb 查询中给了我这个结果
{"_id" : 1, "color" : "red", "year" : 2019},
{"_id" : 2, "color" : "blue", "year" : 2018},
{"_id" : 3, "color" : "green", "year" : 2020}
,在 php 中我得到了这样的结果:
array(3) {
[0] => array(3) {
["_id"] => int(1),
["color"] => string(3) "red"
["year"] => int(2019),
},
[1] => array(3) {
["_id"] => int(2),
["color"] => string(4) "blue"
["year"] => int(2018),
},
[2] => array(3) {
["_id"] => int(3),
["color"] => string(5) "green"
["year"] => int(2020),
}
}
我需要的是这样的结果:
array(3) {
["red"] => array(3) {
["_id"] => int(1),
["color"] => string(3) "red"
["year"] => int(2019),
},
["blue"] => array(3) {
["_id"] => int(2),
["color"] => string(4) "blue"
["year"] => int(2018),
},
["green"] => array(3) {
["_id"] => int(3),
["color"] => string(5) "green"
["year"] => int(2020),
}
}
所以换句话说,我想将文档结果作为数组返回,键为 $color每个文档的。 我所做的是循环一次抛出结果并复制到一个新数组中,如下所示:
newArray = [];
foreach($query as $doc){
$newArray[$doc['color']] = $doc;
}
现在 newArray 具有我需要的结构,但我想直接从 mongo 实现它,这样 php 服务器端就不必在存在时执行该工作有数千份文件。
My aggregation give me this results in mongodb query
{"_id" : 1, "color" : "red", "year" : 2019},
{"_id" : 2, "color" : "blue", "year" : 2018},
{"_id" : 3, "color" : "green", "year" : 2020}
and in php I have the results like this:
array(3) {
[0] => array(3) {
["_id"] => int(1),
["color"] => string(3) "red"
["year"] => int(2019),
},
[1] => array(3) {
["_id"] => int(2),
["color"] => string(4) "blue"
["year"] => int(2018),
},
[2] => array(3) {
["_id"] => int(3),
["color"] => string(5) "green"
["year"] => int(2020),
}
}
what I need is to have it like this:
array(3) {
["red"] => array(3) {
["_id"] => int(1),
["color"] => string(3) "red"
["year"] => int(2019),
},
["blue"] => array(3) {
["_id"] => int(2),
["color"] => string(4) "blue"
["year"] => int(2018),
},
["green"] => array(3) {
["_id"] => int(3),
["color"] => string(5) "green"
["year"] => int(2020),
}
}
So in words, I want to return the documents results as an array with the key as the $color of each document.
What I did is to loop one time throw the results and copy in a new array as follow:
newArray = [];
foreach($query as $doc){
$newArray[$doc['color']] = $doc;
}
and now newArray have the structure I need but I want to achieve it directly from mongo so the php server side not have to do the work when there are thousand of documents.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
听起来将这两个步骤添加到聚合中可以完成这项工作:
返回:
It sounds like adding these two steps to your aggregation can do the job:
Returning: