mongo group 쿼리 필드 유지 방법
여러분.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 },
}
}]);
[댓글 삽입 실패]
답을 찾으러 왔는데, (특히 나이 때문에) 선택한 답변이 마음에 들지 않았습니다.보다 나은 솔루션(적용된)을 찾을 수 있었습니다.
db.test.aggregate({
$group: {
_id: '$name',
person: { "$first": "$$ROOT" },
count: { $sum: 1 }
},
{
"$replaceRoot": { "newRoot": { "$mergeObjects": ["$person", { count: "$count" }]} }
}
}
참고로 첫 번째 문서만 보관하고 싶은 경우 $addToSet For를 사용할 수 있습니다.예를 들어 사용할 수 있습니다.
db.test.aggregate({
$group: {
_id: '$name',
name : { $addToSet: '$name' }
age : { $addToSet: '$age' },
count: { $sum: 1 }
}
}
이거 드셔보세요.
db.test.aggregate({
{ $group:
{ _id: '$name',count: { $sum: 1 }, data: { $push: '$$ROOT' } } },
{
$project: {
_id:0,
data:1,
count :1
}
}
}
와 함께 사용$$ROOT
문서를 작성한 후 첫 번째 필드와 함께 사용합니다.
db.test.aggregate([
{ "$group": {
"_id": "$name",
"doc": { "$first": "$$ROOT" }
}},
{ "$replaceRoot": { "newRoot": "$doc" }}
])
여러 개의 필드가 있는 문서에서 동일한 문제에 직면한 경우 빠른 업데이트입니다.조합의 힘을 사용할 수 있습니다.$replaceRoot
파이프라인 단계와$mergeObjects
파이프라인 오퍼레이터.
db.users.aggregate([
{
$group: {
_id: '$name',
user: { $first: '$$ROOT' },
count: { $sum: 1 }
},
},
{
$replaceRoot: {
newRoot: { $mergeObjects: [{ count: '$count' }, '$user'] }
}
}
])
이게 내가 한 일이야, 잘 작동해.
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
}
}])
나는 몰랐다.group
도우미이지만 Aggregation Framework를 사용하려면 반환할 필드를 지정해야 합니다.틀렸다면 정정해 주세요.하지만 SQL에서는 어쨌든 그렇게 해야 합니다.
앞에서 설명한 Aggregation Framework에서는 다음과 같이 작업을 수행할 수 있습니다.
db.test.aggregate({
$group: {
_id: { name: "$name", city: "$city", fieldName: "$fieldName" },
count: { $sum: 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
}
모든 필드를 투영하려면 아래 쿼리를 사용하십시오.
db.persons.aggregate({
{ $group: { _id: '$name', data: { $push: '$$ROOT' }, total: { $sum: 1 }} },
{
$project: {
_id:0,
data:1,
total :1
}
}
}
$first 옵션과 함께 사용하는 모든 것을 사전에 넣고 마지막에 추출하는 것을 좋아합니다.
{'$set':
{'collection_name':
'collection_item1': '$collection_item1',
'collection_item2': '$collection_item2',
...
}
}
이제 사전을 복사하기만 하면 모든 정보를 한 번에 하나씩 가지고 다닐 필요가 없어집니다.
{'$group':
'_id': ['$id'],
'collection_name': {'$first': '$collection_name'}
}
답변은 다음과 같습니다.>>>>
$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();
언급URL : https://stackoverflow.com/questions/16662405/mongo-group-query-how-to-keep-fields
'programing' 카테고리의 다른 글
HTTPS를 통한 HTTP 쿠키 및 Ajax 요청 (0) | 2023.03.29 |
---|---|
wp_enqueue_script()와 wp_register_script()의 차이점은 무엇입니까? (0) | 2023.03.29 |
Jasmine에서 jQuery AJAX 이벤트를 확인하려면 어떻게 해야 합니까? (0) | 2023.03.29 |
Typescript/OnKeyPress에 대한 올바른 매개 변수 유형은 무엇입니까? (0) | 2023.03.29 |
PUT 메서드를 Angular의 $http와 함께 사용할 때 쿼리 문자열에 매개 변수 추가 (0) | 2023.03.29 |