123

大家。在 mongo 组查询中,结果仅显示参数中的键。如何保留每个组中的第一个文档,如 mysql 查询组。例如:

-------------------------------------------------------------------------
|  name  | age  |  sex  | province |   city   |   area   |   address     |
-------------------------------------------------------------------------
| ddl1st | 22   | 纯爷们 |  BeiJing |  BeiJing | ChaoYang | QingNianLu    |
| ddl1st | 24   | 纯爷们 |  BeiJing |  BeiJing | XuHui    | ZhaoJiaBangLu |
|  24k   | 220  | ...   |  ....    |  ...     | ...      | ...           |
-------------------------------------------------------------------------



db.users.group({key: { name: 1},reduce: function ( curr, result ) { result.count ++ },initial: {count : 0 } })

结果:

[
{
    "name" : "ddl1st",
    "count" : 1
},
{
    "name" : "24k",
    "count" : 1
}
]

如何获得以下内容:

[
   {
   "name" : "ddl1st",
   "age" : 22,
   "sex" : "纯爷们",
   "province" : "BeiJing",
   "city" : "BeiJing",
   "area" : "ChaoYang",
   "address" : "QingNianLu",
   "count" : 1
   },
   {
   "name" : "24k",
   "age" : 220,
   "sex" : "...",
   "province" : "...",
   "city" : "...",
   "area" : "...",
   "address" : "...",
   "count" : 1
}
]
4

12 回答 12

264

如果您想保留有关每个组的第一个匹配条目的信息,您可以尝试聚合如下:

    db.test.aggregate([{
      $group: {
         _id : '$name',
         name : { $first: '$name' },
         age : { $first: '$age' },
         sex : { $first: '$sex' },
         province : { $first: '$province' },
         city : { $first: '$city' },
         area : { $first: '$area' },
         address : { $first: '$address' },
         count : { $sum: 1 },
      }
    }]);
于 2013-05-21T05:40:13.970 回答
35

[编辑以包括评论建议]

我来这里是为了寻找答案,但对所选答案不满意(尤其是考虑到它的年龄)。我发现这个答案是一个更好的解决方案(改编):

db.test.aggregate({
  $group: {
    _id: '$name',
   person: { "$first": "$$ROOT" },
   count: { $sum: 1 }
  },
  {
    "$replaceRoot": { "newRoot": { "$mergeObjects": ["$person", { count: "$count" }]} }
  }
}
于 2019-05-08T13:39:02.193 回答
23

顺便说一句,如果你不想只保留第一个文档,你可以使用$addToSet 例如:

db.test.aggregate({
  $group: {
    _id: '$name',
    name : { $addToSet: '$name' }
    age : { $addToSet: '$age' },
    count: { $sum: 1 }
  }
}
于 2019-05-15T08:49:26.527 回答
11

你可以试试这个

db.test.aggregate({
      { $group: 
            { _id: '$name',count: { $sum: 1 }, data: { $push: '$$ROOT' } } },
      {
        $project: {
          _id:0,
          data:1,
          count :1
        }
      }

}
于 2019-07-24T09:10:10.600 回答
9

$first与文档一起使用$$ROOT,然后$replaceRoot与第一个字段一起使用。

db.test.aggregate([
  { "$group": {
    "_id": "$name",
    "doc": { "$first": "$$ROOT" }
  }},
  { "$replaceRoot": { "newRoot": "$doc" }}
])
于 2020-05-03T21:36:05.350 回答
6

如果您在处理具有多个字段的文档时遇到相同问题,只需快速更新即可。可以利用$replaceRoot流水线级和$mergeObjects流水线算子相结合的力量。

db.users.aggregate([
  {
    $group: {
      _id: '$name',
      user: { $first: '$$ROOT' },
      count: { $sum: 1 }
    },
  },
  {
    $replaceRoot: {
      newRoot: { $mergeObjects: [{ count: '$count' }, '$user'] }
    }
  }
])
于 2020-03-03T17:19:19.917 回答
5

这就是我所做的,它工作正常。

db.person.aggregate([
{
  $group: { _id: '$name'}, // pass the set of field to be grouped
   age : { $first: '$age' }, // retain remaining field
   count: { $sum: 1 } // count based on your group
},
{
  $project:{
       name:"$_id.name",
       age: "$age",
       count: "$count",
       _id:0 
  }
}])
于 2019-08-20T03:23:55.037 回答
1

我不知道.grouphelper,但如果您更喜欢使用Aggregation Framework,那么您必须指定要返回的字段。如果我错了,请纠正我,但在 SQL 中,无论如何你都必须这样做。

好吧,这就是使用前面提到的聚合框架的方法:

db.test.aggregate({
  $group: {
    _id: { name: "$name", city: "$city", fieldName: "$fieldName" },
    count: { $sum: 1 }
  }
})
于 2013-05-21T05:12:32.257 回答
1

我创建了这个函数来概括反转展开阶段......如果你们遇到任何错误,请告诉我,但它对我来说效果很好!

const createReverseUnwindStages = unwoundField => {
  const stages = [
    //
    // Group by the unwound field, pushing each unwound value into an array,
    //
    // Store the data from the first unwound document
    // (which should all be the same apart from the unwound field)
    // on a field called data.
    // This is important, since otherwise we have to specify every field we want to keep individually.
    //
    {
      $group: {
        _id: '$_id',
        data: {$first: '$$ROOT'},
        [unwoundField]: {$push: `$${unwoundField}`},
      },
    },

    //
    // Copy the array of unwound fields resulting from the group into the data object,
    // overwriting the singular unwound value
    //
    {
      $addFields: {[`data.${unwoundField}`]: `$${unwoundField}`},
    },

    //
    // Replace the root with our data object
    //
    {
      $replaceRoot: {
        newRoot: '$data',
      },
    },
  ]

  return stages
}
于 2019-10-16T12:14:50.897 回答
1

如果您想投影所有字段文档,请使用以下查询。

db.persons.aggregate({
      { $group: { _id: '$name', data: { $push: '$$ROOT' }, total: { $sum: 1 }} },
      {
        $project: {
          _id:0,
          data:1,
          total :1
        }
      }
}
于 2020-07-11T10:54:49.767 回答
0

我喜欢将要与 $first 选项一起使用的所有内容放入字典中,以便在最后提取。

{'$set': 
  {'collection_name':
    'collection_item1': '$collection_item1',
    'collection_item2': '$collection_item2',
    ...
  }
}

现在,只需复制字典,您就不必一次又一次地翻找所有的信息 1!

{'$group':
  '_id': ['$id'],
  'collection_name': {'$first': '$collection_name'}
}
于 2021-07-06T23:43:21.010 回答
-2

这是答案>>>>

    $m = new \MongoDB\Driver\Manager();

    $command = new \MongoDB\Driver\Command([
        'aggregate' => 'mytestusers',
        'pipeline' => [
            ['$match' => ['name' => 'Pankaj Choudhary']],

            ['$unwind'=>'$skills'],
            ['$lookup' => array('from'=>'mytestskills','localField'=>'skills','foreignField'=>'_id','as'=>'sdfg')],
            ['$unwind'=>'$sdfg'],

            ['$group'=>array('_id'=>array('_id'=>'$_id','name'=>'$name','email'=>'$email'),'skills'=>array('$push'=>'$skills'),'sdfg'=>array('$push'=>'$sdfg'))],


        ],
        'cursor' => new \stdClass,
    ]);
    $cursor = $m->executeCommand('targetjob-plus', $command);
    $result = $cursor->toArray();
于 2017-05-04T07:37:20.287 回答