MongoDB aggregate()。$ unwind

时间:2014-03-26 14:14:16

标签: javascript mongodb

我有一些看起来像这样的数据(不是真实数据):

 {
      _id:'cust04',
      name:'Diarmuid Rellis',
      address:'Elysium, Passage East',
      county:'Waterford',
      phone:'051-345786',
      email:'dreil@drarch.com',
      quotations:[
         {
            _id:'quot03',
            supplier_ref:'A2006',
            date_received: new Date('2013-05-12T00:00:00'),
            date_returned: new Date('2013-05-15T00:00:00'),
            supplier_price:35000.00,
            customer_price:35000.00,
            orders:[
               {
                  _id:'ord03',
                  order_date: new Date('2013-05-20T00:00:00'),
                  del_date: new Date('2013-08-12T00:00:00'),
                  del_address:'Elysium, Passage East, Co. Waterford',
                  status:'BALPAID'
               }
            ]
         },
         {
            _id:'quot04',
            supplier_ref:'A2007',
            date_received: new Date('2013-08-10T00:00:00'),
            date_returned: new Date('2013-08-12T00:00:00'),
            supplier_price:29600.00,
            customer_price:29600.00,
            orders:[
               {
                  _id:'ord04',
                  order_date: new Date('2014-03-20T00:00:00'),
                  del_date: new Date('2014-05-12T00:00:00'),
                  del_address:'Elysium, Passage East, Co. Waterford',
                  status:'INPROD'
               }
            ]
         }
      ]
   }

我正在尝试展开报价和订单数组,并获得生产中所有订单的预测,其中包括每个订单的客户名称,supplier_ref和订单日期。

这是我的问题:

 db.customers.aggregate([
    { $unwind: "$quotations" },
    { $unwind: "$quotations.orders" },
    { $match: { 'quotations.orders.status': 'INPROD' } },
    {
    $project: {
        name: 1,
            supplier_ref: "$quotations.supplier_ref",
            order_id: "$quotations.orders._id",
            order_date: "$quotations.orders.order_date"
            }     
    },
    {
        $group: {
            _id: "$order_id"
        }

    }
], function (err, results) {
console.log(results);
})

查询成功运行,但只提供订单ID,而不是所需的任何其他字段。我错过了什么?

修改

我希望得到如下结果:

 "result": [
  {
    "_id" : "orderid01",
    "name" : "Joe Bloggs",
     "supplier_ref" : "A1234",
     "date_ordered" : "2012-04-14"
  },
  {
    "_id" : "orderid02",
    "name" : "Joe Bloggs",
     "supplier_ref" : "A1235",
     "date_ordered" : "2012-04-16"
  }
]

当我向“组”功能添加额外字段时,如下所示:

    $group: {
        _id: "$order_id", 
        supplier_ref: "$supplier_ref"

    }

我收到错误:“必须将组聚合字段'supplier_ref'定义为对象内的表达式”。我是否必须以某种方式将其与结果对象相关联?

1 个答案:

答案 0 :(得分:1)

删除组功能完全产生了我想要的结果。