$position 연산자는 새 요소를 삽입해야 하는 배열의 위치를 지정하는 데 사용됩니다. 이 연산자는 끝에 추가하지 않고 배열의 특정 인덱스에서 요소를 삽입해야 하는 경우에 유용합니다.
문법
{
$push: {
<arrayField>: {
$each: [<value1>, <value2>],
$position: <index>
}
}
}
매개 변수
| 매개 변수 | Description |
|---|---|
<arrayField> |
업데이트할 배열이 포함된 문서의 필드입니다. |
<value1>, <value2>, ... |
배열에 삽입할 값입니다. |
<index> |
값을 삽입할 위치입니다. |
예시
스토어 컬렉션에서 이 샘플 문서를 고려합니다.
{
"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
"name": "First Up Consultants | Beverage Shop - Satterfieldmouth",
"location": {
"lat": -89.2384,
"lon": -46.4012
},
"staff": {
"totalStaff": {
"fullTime": 8,
"partTime": 20
}
},
"sales": {
"totalSales": 75670,
"salesByCategory": [
{
"categoryName": "Wine Accessories",
"totalSales": 34440
},
{
"categoryName": "Bitters",
"totalSales": 39496
},
{
"categoryName": "Rum",
"totalSales": 1734
}
]
},
"promotionEvents": [
{
"eventName": "Unbeatable Bargain Bash",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 6,
"Day": 23
},
"endDate": {
"Year": 2024,
"Month": 7,
"Day": 2
}
},
"discounts": [
{
"categoryName": "Whiskey",
"discountPercentage": 7
},
{
"categoryName": "Bitters",
"discountPercentage": 15
},
{
"categoryName": "Brandy",
"discountPercentage": 8
},
{
"categoryName": "Sports Drinks",
"discountPercentage": 22
},
{
"categoryName": "Vodka",
"discountPercentage": 19
}
]
},
{
"eventName": "Steal of a Deal Days",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 9,
"Day": 21
},
"endDate": {
"Year": 2024,
"Month": 9,
"Day": 29
}
},
"discounts": [
{
"categoryName": "Organic Wine",
"discountPercentage": 19
},
{
"categoryName": "White Wine",
"discountPercentage": 20
},
{
"categoryName": "Sparkling Wine",
"discountPercentage": 19
},
{
"categoryName": "Whiskey",
"discountPercentage": 17
},
{
"categoryName": "Vodka",
"discountPercentage": 23
}
]
}
]
}
예제 1: 배열 필드의 특정 인덱스 위치에 요소 삽입
이 쿼리는 특정 문서의 배열에서 두 번째 위치(인덱스 1)에 #NewArrival 태그 tag 를 삽입합니다.
db.stores.update({
_id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5"
}, {
$push: {
tag: {
$each: ["#NewArrival"],
$position: 1
}
}
})
업데이트된 문서에는 태그 배열에 다음 값이 있습니다.
{
"_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
"tag": [
"#ShopLocal",
"#NewArrival",
"#FashionStore",
"#SeasonalSale",
"#FreeShipping",
"#MembershipDeals"
]
}
관련 콘텐츠
- MongoDB에서 Azure DocumentDB로 마이그레이션하기 위한 옵션을 검토합니다.
- MongoDB와의 기능 호환성에 대해 자세히 알아보세요.