大家。 在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
}
]
答案 0 :(得分:156)
如果您想保留每个组的第一个匹配条目的信息,您可以尝试汇总,如:
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 }
}
}
答案 1 :(得分:4)
如果具有多个字段的文档面临相同的问题,请快速更新。
可以使用组合$replaceRoot
流水线阶段和$mergeObjects
流水线运算符的功能。
db.users.aggregate([
{
$group: {
_id: '$name',
user: { $first: '$$ROOT' },
count: { $sum: 1 }
},
},
{
$replaceRoot: {
newRoot: { $mergeObjects: [{ count: '$count' }, '$user'] }
}
}
])
答案 2 :(得分:4)
在$$ROOT
文档中使用$first
,然后在第一个字段中使用$replaceRoot
。
db.test.aggregate([
{ "$group": {
"_id": "$name",
"doc": { "$first": "$$ROOT" }
}},
{ "$replaceRoot": { "newRoot": "$doc" }}
])
答案 3 :(得分:2)
这就是我所做的,效果很好。
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
}
}])
答案 4 :(得分:1)
我不了解.group
帮助器,但如果您更喜欢使用Aggregation Framework,那么您必须指定要返回的字段。如果我错了,请纠正我,但在SQL中你无论如何都必须这样做。
嗯,这就是你用前面提到的聚合框架做的事情:
db.test.aggregate({
$group: {
_id: { name: "$name", city: "$city", fieldName: "$fieldName" },
count: { $sum: 1 }
}
})
答案 5 :(得分:1)
顺便说一句,如果您不仅要保留第一个文档,还可以使用$addToSet 例如:
db.test.aggregate({
$group: {
_id: '$name',
name : { $addToSet: '$name' }
age : { $addToSet: '$age' },
count: { $sum: 1 }
}
}
答案 6 :(得分: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
}
答案 7 :(得分:0)
我来这里寻找答案,但对所选答案不满意(特别是考虑到年龄)。我发现this answer是更好的解决方案(已适应):
db.test.aggregate({
$group: {
_id: '$name',
person: { "$first": "$$ROOT" },
count: { $sum: 1 }
},
{
"$replaceRoot": { "newRoot": "$person" }
}
}
答案 8 :(得分:0)
您可以尝试一下
db.test.aggregate({
{ $group:
{ _id: '$name',count: { $sum: 1 }, data: { $push: '$$ROOT' } } },
{
$project: {
_id:0,
data:1,
count :1
}
}
}
答案 9 :(得分:0)
如果要投影所有字段,请在查询下方使用此文件。
db.persons.aggregate({
{ $group: { _id: '$name', data: { $push: '$$ROOT' }, total: { $sum: 1 }} },
{
$project: {
_id:0,
data:1,
total :1
}
}
}
答案 10 :(得分:0)
我喜欢把将要与 $first 选项一起使用的所有内容放入字典中,以便在最后提取。
0
现在,只需复制字典,您就不再需要一次拖着所有这些信息 1!
{'$set':
{'collection_name':
'collection_item1': '$collection_item1',
'collection_item2': '$collection_item2',
...
}
}
答案 11 :(得分:-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();