如何从汇总$ match和$ group查询中删除_id

时间:2019-07-26 09:38:11

标签: node.js mongodb mongoose

我正在尝试显示按传入的特定段分组的唯一记录。

我在邮递员中的输出看起来像这样:

"subcats": [
  {
    "_id": {
      "subcategory": {
        "_id": "5d2b42c47b454712f4db7c37",
        "name": "shirts"
      }
    }
  }
]

当我想要的输出是:

"subcats": [
  {
        "_id": "5d2b42c47b454712f4db7c37",
        "name": "shirts"
  }
]

数据库中产品的示例:

    "_id": "5d39eff7a48e6e30ace831dc",
    "name": "A colourful shirt",
    "description": "A nice colourful t-shirt",
    "category": {
        "_id": "5d35faa67b19e32ab3dc91ec",
        "name": "clothing",
        "catSlug": "clothing"
    },
    "subcategory": {
        "_id": "5d2b42c47b454712f4db7c37",
        "name": "shirts",
        "catSlug": "shirts"
    },
    "price": 19
}

我不希望顶层_id内嵌所有内容。

我尝试使用$project,但是最后我得到一个空数组。

  const products = await Product.find({ "category.catSlug": catslug }).select({
    name: 1,
    description: 1,
    price: 1,
    category: 1
  });

const subcats = await Product.aggregate([
  { $match: { "category.catSlug": catslug } },
  { $group: { _id: { subcategory: "$subcategory" } } }
  { $project: { _id: 0, name: 1 } }
]);

Promise.all([products, subcats]);
  res.status(200).json({
    products,
    subcats
  });

2 个答案:

答案 0 :(得分:0)

您好,您需要在投影时在其他字段中分配所需的数据,然后将_id定义为0,如下所示

      {$project:{subcat_data:'$_id.subcategory'},_id:0}

答案 1 :(得分:0)

我从您的问题中了解到,您需要按类别列出所有产品,并将所有子类别作为列表。

以下是汇总:

db.getCollection('test').aggregate([
 { $match: { "category.catSlug": "clothing" } },
 { $group: { _id: '$subcategory.name', subCategory: { $first : "$subcategory" }}},
 { $group: { _id: null, subcats: { $push:  {_id: "$subCategory._id", name: "$subCategory.name" }}}},
 { $project: {_id: 0, subcats: 1}}
]);
  

注意:您可以直接按“ $ subcategory”,但它在对象内部将有catSlug

输出:

{
  "_id" : null,
  "subcats" : [{
    "_id" : "5d2b42c47b454712f4db7c37",
    "name" : "shirts"
  }, 
  {
    "_id" : "5d2b42c47b454712f4db7c37",
    "name" : "pents"
  }]
}

希望获得帮助!