MongoDb-防止在按ID分组期间推送空值,并在结果中包括该空ID文档

时间:2019-04-08 11:56:23

标签: mongodb mongoose

我想按ID对文档进行分组而不对空值进行分组,并且我也需要对不对ID进行分组的空ID文档。

我试图在分组之前使用match,以防止按空值分组,但是这样我就无法检索空id文档。

示例架构:

{
    "txnId": String,
    "orderId": String
}

我的文档:

{
  "txnId": "M336GRNT0B4WI2VP0NBMW",
  "orderId": "5CAA42CC103C385B08E9C84B",
},
{
  "txnId": "N8E1JSL481KKR41TRDYTO",
  "orderId": "5CAA42CC103C385B08E9C84B",
},
{
   "txnId": "XD7N78WPYXXC06AHXLZV5",
   "orderId": null
},
{
  "txnId": "WTQVRH3UXKJUFE4NAEVRL",
  "orderId": null
}

分组阶段:

 '$group': {
              '_id': '$orderId',
              'orders': {
                     '$push': '$$ROOT'
              }
  }

我得到的结果是:

 {
     "_id": "5CAA42CC103C385B08E9C84B",
     "orders":[
     {
       "txnId": "M336GRNT0B4WI2VP0NBMW",
       "orderId": "5CAA42CC103C385B08E9C84B"
     },
     {
       "txnId": "N8E1JSL481KKR41TRDYTO",
       "orderId": "5CAA42CC103C385B08E9C84B",
     }
     ]
},
{
      "_id": null;
      "orders":[
      {
          "txnId": "XD7N78WPYXXC06AHXLZV5",
          "orderId": null
      },
      {
         "txnId": "WTQVRH3UXKJUFE4NAEVRL",
         "orderId": null
      }
      ]
 }

但是我想要拥有的是:

  {
     "_id": "5CAA42CC103C385B08E9C84B",
     "orders":[
     {
       "txnId": "M336GRNT0B4WI2VP0NBMW",
       "orderId": "5CAA42CC103C385B08E9C84B"
     },
     {
       "txnId": "N8E1JSL481KKR41TRDYTO",
       "orderId": "5CAA42CC103C385B08E9C84B",
     }
     ]
},
{
    "txnId": "XD7N78WPYXXC06AHXLZV5",
    "orderId": null
},
{
     "txnId": "WTQVRH3UXKJUFE4NAEVRL",
     "orderId": null
}

0 个答案:

没有答案