문서 메뉴

문서 홈애플리케이션 개발MongoDB 매뉴얼

$mergeObjects (애그리게이션)

이 페이지의 내용

  • 정의
  • 구문
  • 행동
  • 예제
$mergeObjects

여러 문서를 하나의 문서로 결합합니다.

$mergeObjects 이 단계에서 사용할 수 있습니다:

$bucket, $bucketAuto 또는 $group 단계 축적자로 사용되는 경우 $mergeObjects 의 구문은 다음과 같습니다.

{ $mergeObjects: <document> }

다른 표현식( $bucket, $bucketAuto$group 단계 포함)에 사용되지만 축적자로는 사용되지 않는 경우 $mergeObjects 는 다음 구문을 가집니다.

{ $mergeObjects: [ <document1>, <document2>, ... ] }

<document>는 문서로 해석되는 모든 유효한 표현식이 될 수 있습니다.

$mergeObjectsnull 피연산자를 무시합니다. $mergeObjects 에 대한 모든 피연산자가 null로 확인되면 $mergeObjects 는 빈 문서 { } 를 반환합니다.

$mergeObjects 는 문서를 병합할 때 필드 값을 덮어씁니다. 병합할 문서에 동일한 필드 이름이 포함된 경우, 결과 문서의 필드에는 해당 필드에 대해 병합된 마지막 문서의 값이 포함됩니다.

예제
결과
{ $mergeObjects: [ { a: 1 }, null ] }
{ a: 1 }
{ $mergeObjects: [ null, null ] }
{ }
{
$mergeObjects: [
{ a: 1 },
{ a: 2, b: 2 },
{ a: 3, c: 3 }
]
}
{ a: 3, b: 2, c: 3 }
{
$mergeObjects: [
{ a: 1 },
{ a: 2, b: 2 },
{ a: 3, b: null, c: 3 }
]
}
{ a: 3, b: null, c: 3 }

다음 문서를 사용하여 컬렉션 orders를 생성합니다.

db.orders.insertMany( [
{ "_id" : 1, "item" : "abc", "price" : 12, "ordered" : 2 },
{ "_id" : 2, "item" : "jkl", "price" : 20, "ordered" : 1 }
] )

다음 문서로 다른 컬렉션 items를 만듭니다.

db.items.insertMany( [
{ "_id" : 1, "item" : "abc", description: "product 1", "instock" : 120 },
{ "_id" : 2, "item" : "def", description: "product 2", "instock" : 80 },
{ "_id" : 3, "item" : "jkl", description: "product 3", "instock" : 60 }
] )

다음 작업은 먼저 $lookup 단계를 사용하여 item 필드를 기준으로 두 컬렉션을 조인한 다음$replaceRoot에서 $mergeObjects 를 사용하여 itemsorders 에서 조인된 문서를 병합합니다.

db.orders.aggregate( [
{
$lookup: {
from: "items",
localField: "item", // field in the orders collection
foreignField: "item", // field in the items collection
as: "fromItems"
}
},
{
$replaceRoot: { newRoot: { $mergeObjects: [ { $arrayElemAt: [ "$fromItems", 0 ] }, "$$ROOT" ] } }
},
{ $project: { fromItems: 0 } }
] )

이 작업은 다음 문서를 반환합니다.

{
_id: 1,
item: 'abc',
description: 'product 1',
instock: 120,
price: 12,
ordered: 2
},
{
_id: 2,
item: 'jkl',
description: 'product 3',
instock: 60,
price: 20,
ordered: 1
}

다음 문서를 사용하여 컬렉션 sales를 생성합니다.

db.sales.insertMany( [
{ _id: 1, year: 2017, item: "A", quantity: { "2017Q1": 500, "2017Q2": 500 } },
{ _id: 2, year: 2016, item: "A", quantity: { "2016Q1": 400, "2016Q2": 300, "2016Q3": 0, "2016Q4": 0 } } ,
{ _id: 3, year: 2017, item: "B", quantity: { "2017Q1": 300 } },
{ _id: 4, year: 2016, item: "B", quantity: { "2016Q3": 100, "2016Q4": 250 } }
] )

다음 작업은 $mergeObjects $group item 필드를 기준으로 문서를 그룹화하는 단계에서 를 축적자로 사용합니다.

참고

축적자로 사용되는 경우 $mergeObjects 연산자는 단일 피연산자를 허용합니다.

db.sales.aggregate( [
{ $group: { _id: "$item", mergedSales: { $mergeObjects: "$quantity" } } }
] )

이 작업은 다음 문서를 반환합니다.

{
_id: 'A',
mergedSales: { '2017Q1': 500, '2017Q2': 500, '2016Q1': 400, '2016Q2': 300, '2016Q3': 0, '2016Q4': 0 }
},
{
_id: 'B',
mergedSales: { '2017Q1': 300, '2016Q3': 100, '2016Q4': 250 }
}

참고

병합할 문서에 동일한 필드 이름이 포함된 경우 결과 문서의 필드는 해당 필드에 대해 병합된 마지막 문서의 값을 가집니다.

← $median(애그리게이션)
$meta →

이 페이지의 내용