mongo组查询如何保持字段

每个人。 在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 } ] 

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

 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 } } } 

我不知道.group助手,但是如果你喜欢用聚合框架 ,那么你将不得不指定要返回的字段。 纠正我,如果我错了,但在SQL中,你将不得不这样做。

那么,这就是你如何使用前面提到的聚合框架来完成的:

 db.test.aggregate({ $group: { _id: { name: "$name", city: "$city", fieldName: "$fieldName" }, count: { $sum: 1 } } }) 

这是答案>>>>

  $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();