Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在子文档中按一个匹配元素分组-Mongodb_Mongodb - Fatal编程技术网

如何在子文档中按一个匹配元素分组-Mongodb

如何在子文档中按一个匹配元素分组-Mongodb,mongodb,Mongodb,假设我有以下收藏 [ { "items": { "item": [ { "@pid": "131", "text": "Apple" }, { "@pid": "61", "text": "Mango" }, { "@pid": "92", "text": "cherry"

假设我有以下收藏

[
  {
    "items": {
      "item": [
        {
          "@pid": "131",
          "text": "Apple"
        },
        {
          "@pid": "61",
          "text": "Mango"
        },
        {
          "@pid": "92",
          "text": "cherry"
        },
        {
          "@pid": "27",
          "text": "grape"
        },
        {
          "@pid": "34",
          "text": "dragonfruit"
        }
      ]
    },
    "type": "A"
  },
  {
    "items": {
      "item": [
        {
          "@pid": "131",
          "text": "Apple"
        },
        {
          "@pid": "27",
          "text": "grape"
        },
        {
          "@pid": "34",
          "text": "dragonfruit"
        }
      ]
    },
    "type": "B"
  },
  {
    "items": {
      "item": [
        {
          "@pid": "131",
          "text": "Apple"
        }
      ]
    },
    "type": "A"
  }
]
我想得到苹果或芒果的销售类型,按商品名称分组。对于上述集合,输出为:

{
    "_id": "Apple",
    "items" : [
        "A",
        "B",
        "A"
    ]
},
{
    "_id": "Mango",
    "items" : [
        "A"
    ]
}

我尝试了以下查询,但未返回任何结果:

db.collection.aggregate([

     {
         $match : {
             'items.item.text' : {$regex : 'Apple|Mango'}
         }

     },
     {
        $project : {
            type : "$type"
        }
     },
     {
         $group : {
             _id : '$items.item',
                types : {$push : '$type'}

         }
     }


 ])
我认为,即使这样做有效,它也会按照整个“items.item”进行分组。我哪里做错了

附言:我无权更改文件的格式


事先非常感谢。

你的方向是对的。您需要使用运算符,而不需要聚合中的
$project
阶段。以下查询将非常有用:

db.collection.aggregate([
{
$unwind:“$items.item”
},
{
$match:{
“items.item.text”:{
$regex:“苹果|芒果”
}
}
},
{
$group:{
_id:“$items.item.text”,
类型:{
$push:“$type”
}
}
}
])

哦,那太好了!我开始认为这是不可能的。非常感谢。很乐意帮忙:)