반응형
Mongo 그룹 및 푸시: 모든 필드 푸시
문서의 모든 필드를 쉽게 "$push"할 수 있는 방법이 있습니까?예를 들어 다음과 같습니다.
Mongo 컬렉션이 있다고 가정해 보겠습니다.
{author: "tolstoy", title:"war & peace", price:100, pages:800}
{author: "tolstoy", title:"Ivan Ilyich", price:50, pages:100}
저자를 기준으로 그룹화하고 각 저자에 대해 저자의 전체 책 개체를 나열합니다.
{ author: "tolstoy",
books: [
{author: "tolstoy", title:"war & peace", price:100, pages:800}
{author: "tolstoy", title:"Ivan Ilyich", price:50, pages:100}
]
}
모든 필드를 명시적으로 푸시하면 이 작업을 수행할 수 있습니다.
{$group: {
_id: "$author",
books:{$push: {author:"$author", title:"$title", price:"$price", pages:"$pages"}},
}}
하지만 다음과 같은 지름길이 있나요?
// Fictional syntax...
{$group: {
_id: "$author",
books:{$push: "$.*"},
}}
$$ROOT를 사용할 수 있습니다.
{ $group : {
_id : "$author",
books: { $push : "$$ROOT" }
}}
여기에서 찾을 수 있습니다: mongodb Aggregate를 사용하여 전체 문서를 검색하는 방법
사실 당신은 당신이 말하는 것을 전혀 달성할 수 없습니다.당신은 $unwind가 필요합니다.
db.collection.aggregate([
{$unwind: "$books"},
{$group: {
_id: "$author",
books:{$push: {
author:"$books.author",
title:"$books.title",
price:"$books.price",
pages:"$books.pages"
}},
}}
])
이것이 집약된 어레이를 처리하는 방법입니다.
또한 모든 필드를 바로 입력하기 위해 찾으시는 항목은 아직 존재하지 않습니다.
그러나 구체적으로 해야 할 일이 있기 때문에 문서를 재구성할 때 현재 상태로는 그렇게 할 수 없습니다.
모든 필드를 명시적으로 작성하지 않으려는 경우(문서에 여러 필드가 있고 모든 필드가 필요한 경우) Map-Reduce를 사용하여 작성할 수도 있습니다.
db.books.mapReduce(
function () { emit(this.author, this); },
function (key, values) { return { books: values }; },
{
out: { inline: 1 },
finalize: function (key, reducedVal) { return reducedVal.books; }
}
)
언급URL : https://stackoverflow.com/questions/22150205/mongo-group-and-push-pushing-all-fields
반응형
'programing' 카테고리의 다른 글
JDeveloper/SQL Developer가 자격 증명을 유지하기 위해 사용하는 암호화 기술을 아는 사람이 있습니까? (0) | 2023.03.04 |
---|---|
여러 개의 대소문자가 있는 Tymleaf 스위치 문 (0) | 2023.03.04 |
React.createRef를 사용하는 경우 전류는 항상 null입니다. (0) | 2023.03.04 |
스프링 부트 2 및 마이크로미터를 사용하여 서비스 방법을 측정하는 방법 (0) | 2023.02.27 |
사이드바 외부에서 위젯을 사용하시겠습니까? (0) | 2023.02.27 |