鉴于文件:
{
"_id" : "8843c0c0-846f-44ae-9b69-a124dd28f4db",
"purchaseOrderData" : {
"purchaseOrderId" : "WI9ZF"
}
}
{
"_id" : "c3fb80fc-75c0-4259-9d5a-1bc6de1ce7d7",
"purchaseOrderData" : {
"purchaseOrderId" : "WJ0DD"
}
}
{
"_id" : "2ae496e6-28f9-4baa-b952-2054a505f658",
"purchaseOrderData" : {
"purchaseOrderId" : "WI8PP"
}
}
{
"_id" : "421ccbed-0824-443f-bf42-3f0049f46c71",
"purchaseOrderData" : {
"purchaseOrderId" : "WI9WH"
}
}
{
"_id" : "5481b1ef-5f0f-4ba1-8210-d704e9650af4",
"purchaseOrderData" : {
"purchaseOrderId" : "WI9ZH"
}
}
{
"_id" : "1640a27a-6577-4240-8aaa-4c4b1334fd6d",
"purchaseOrderData" : {
"purchaseOrderId" : "WJ0DD"
}
}
{
"_id" : "bd95d801-da2d-4556-a223-dcff30b6ab9d",
"purchaseOrderData" : {}
}
{
"_id" : "4880f816-41e7-43bc-bed4-e8574aa9c045",
"purchaseOrderData" : {
"purchaseOrderId" : "WI9LA"
}
}
{
"_id" : "fe651764-aeb4-460e-89fa-474fcec33f19",
"purchaseOrderData" : {}
}
{
"_id" : "4d73431c-85dc-479a-8739-b314d6cd9636",
"purchaseOrderData" : {
"purchaseOrderId" : "WI9LA"
}
}
我想要一个结果:
{
"purchaseOrderData.purchaseOrderId":["_id1","_id2"]
}
例如:
[{
"WI9ZF":["8843c0c0-846f-44ae-9b69-a124dd28f4db"]
},{
"WI9WH":["421ccbed-0824-443f-bf42-3f0049f46c71","5481b1ef-5f0f-4ba1-8210-d704e9650af4"]
}]
答案 0 :(得分:1)
使用聚合框架可以实现紧密的文档形状,但是需要在app服务器端对其进行重塑。
db.leonardo.aggregate([
{
$group:{
"_id":"$purchaseOrderData.purchaseOrderId",
"data":{$push:"$_id"}
}
}])
将为给定的数据集提供此输出:
{ "_id" : "WI9WH", "data" : [ "421ccbed-0824-443f-bf42-3f0049f46c71" ] }
{ "_id" : "WI9ZF", "data" : [ "8843c0c0-846f-44ae-9b69-a124dd28f4db" ] }
{
"_id" : "WJ0DD",
"data" : [
"c3fb80fc-75c0-4259-9d5a-1bc6de1ce7d7",
"1640a27a-6577-4240-8aaa-4c4b1334fd6d"
]
}
{ "_id" : "WI8PP", "data" : [ "2ae496e6-28f9-4baa-b952-2054a505f658" ] }
{ "_id" : "WI9ZH", "data" : [ "5481b1ef-5f0f-4ba1-8210-d704e9650af4" ] }
{ "_id" : null, "data" : [ "bd95d801-da2d-4556-a223-dcff30b6ab9d" ] }
{ "_id" : "WI9LA", "data" : [ "4880f816-41e7-43bc-bed4-e8574aa9c045" ] }