如何在mongodb中使用嵌套组?

时间:2019-05-29 12:43:31

标签: node.js mongodb mongoose

我有一个查询要在哪里对子文档进行分组。我已经尝试了一些示例,但无法正常工作

查询

 Future<Map<String, dynamic>> getData() async {
      var client = http.Client();
      XsProgressHud.show(context);
      //to SHOW Indicator
      setState(() {
        _loading = true;
      });

      var response = await client
          .post(
          Uri.encodeFull(
              ' api url '),
          body:
        {"email":"$username","password":"$password"}

      ).whenComplete(
          client.close);

      var res = json.decode(response.body);

      //to HIDE indicator
      setState(() {
        _loading = false;
      });

      if(response.statusCode <200 || response.statusCode > 400){
        XsProgressHud.hide();
        print("Error");
         throwError();
      }
      if(response.statusCode == 200 ){
        XsProgressHud.hide();
        widget.onSignedIn();
      }

      if (!mounted)
        return {'success': false};

      return json.decode(response.body);
    }
  

此查询返回结果以下

db.getCollection("checklistCombination").aggregate([
  {
    "$lookup": {
      "from": "Users",
      "localField": "userId",
      "foreignField": "_id",
      "as": "user"
    }
  },
  {
    "$lookup": {
      "from": "checklist",
      "localField": "checklistId",
      "foreignField": "_id",
      "as": "linkChecklist"
    }
  },
  { "$unwind": "$linkChecklist" },
  {
    "$lookup": {
      "from": "orderDetail",
      "localField": "linkChecklist.product",
      "foreignField": "productRangeId",
      "as": "orderProduct"
    }
  },
  {
    "$unwind": { "path": "$orderProduct", "preserveNullAndEmptyArrays": true }
  },
  {
    "$lookup": {
      "from": "companysuppliers",
      "localField": "orderProduct.supplierId",
      "foreignField": "_id",
      "as": "comapnySupplier"
    }
  },
  {
    "$unwind": {
      "path": "$comapnySupplier",
      "preserveNullAndEmptyArrays": true
    }
  },
  {
    "$lookup": {
      "from": "suppliers",
      "localField": "comapnySupplier.supplierId",
      "foreignField": "_id",
      "as": "supplier"
    }
  },
  { "$unwind": { "path": "$supplier", "preserveNullAndEmptyArrays": true } },
  {
    "$project": {
      "_id": 1,
      "name": 1,
      "user": 1,
      "linkChecklist": 1,
      "orderProduct": 1,
      "orderProductStatusIndex": {
        "$ifNull": ["$orderProduct.statusIndex", "0"]
      },
      "comapnySupplier": 1,
      "supplier": 1
    }
  },
  { "$match": { "orderProductStatusIndex": "0" } },
  {
    "$group": {
      "_id": "$_id",
      "name": { "$first": "$name" },
      "supplier": {
        "$push": {
          "supplierId": "$supplier._id",
          "supplierName": "$supplier.name",
          "items": { "$sum": "$orderProduct.quantity" }
        }
      }
    }
  }
])

结果您会看到乳制品/水果中的 Bh​​agwandas Bherumal 有两个不同的结果(在数组索引1中)。我想按此字段分组并汇总其项目。

  

预期结果

[{
    "_id" : ObjectId("5cee224b97e765079c8c2839"),
    "name" : "Dairy",
    "supplier" : [ 
        {
            "supplierId" : ObjectId("5cee12a7a01ad50f5c2229ac"),
            "supplierName" : "Bhagwandas Bherumal",
            "items" : 10
        }
    ]
},
{
    "_id" : ObjectId("5cee1a19a01ad50f5c2229f2"),
    "name" : "dairy/fruit",
    "supplier" : [ 
        {
            "supplierId" : ObjectId("5cee12a7a01ad50f5c2229ac"),
            "supplierName" : "Bhagwandas Bherumal",
            "items" : 55
        }, 
        {
            "supplierId" : ObjectId("5cee11f7a01ad50f5c2229a2"),
            "supplierName" : "Agron India PVT. LTD",
            "items" : 55
        }, 
        {
            "supplierId" : ObjectId("5cee12a7a01ad50f5c2229ac"),
            "supplierName" : "Bhagwandas Bherumal",
            "items" : 10
        }
    ]
}]

1 个答案:

答案 0 :(得分:1)

希望这可以解决您的问题:

db.getCollection("checklistCombination").aggregate([
 {
   "$lookup": {
    "from": "Users",
    "localField": "userId",
    "foreignField": "_id",
    "as": "user"
   }
 },
 {
   "$lookup": {
    "from": "checklist",
    "localField": "checklistId",
    "foreignField": "_id",
    "as": "linkChecklist"
   }
 },
 { "$unwind": "$linkChecklist" },
 {
   "$lookup": {
     "from": "orderDetail",
     "localField": "linkChecklist.product",
     "foreignField": "productRangeId",
     "as": "orderProduct"
   }
 },
 {
   "$unwind": { "path": "$orderProduct", "preserveNullAndEmptyArrays": true }
 },
 {
   "$lookup": {
     "from": "companysuppliers",
     "localField": "orderProduct.supplierId",
     "foreignField": "_id",
     "as": "comapnySupplier"
    }
 },
 {
   "$unwind": {
    "path": "$comapnySupplier",
    "preserveNullAndEmptyArrays": true
   }
 },
 {
   "$lookup": {
     "from": "suppliers",
     "localField": "comapnySupplier.supplierId",
     "foreignField": "_id",
     "as": "supplier"
   }
 },
 { "$unwind": { "path": "$supplier", "preserveNullAndEmptyArrays": true } },
 {
   "$project": {
     "_id": 1,
     "name": 1,
     "user": 1,
     "linkChecklist": 1,
     "orderProduct": 1,
     "orderProductStatusIndex": {
        "$ifNull": ["$orderProduct.statusIndex", "0"]
      },
     "comapnySupplier": 1,
     "supplier": 1
   }
 },
 { "$match": { "orderProductStatusIndex": "0" } },
 { $group : {
    _id : {
      _id :  '$_id',
      name : '$name',
      supplierId : "$supplier._id",
      supplierName : "$supplier.name"
    },
    items  : { "$sum": "$orderProduct.quantity"}
  }
 },
 {
   $group : {
     _id : '$_id._id',
     name : { "$first": "$_id.name" },
     supplier : {
         "$push": {
            "supplierId": "$_id.supplierId",
             "supplierName": "$_id.supplierName",
             "items" : '$items'
         }
     }
   }
 }
])