집계하는 동안 MongoDB에 $second에 다른 if가 있습니까?
그래서 나는 MongoDB에서 다음과 같이 계산된 커스텀 필드가 필요합니다.
if( field1 =="A") ->customfield=10
else if(field1 =="B" )->customfield=20
else (field1 =="C" ) ->customfield=15
$project 명세서와 함께 aggregation을 사용하고 있습니다.그러나 $cond 연산자는 otherif(다른 연산자의 하위 분기)를 허용하지 않으며, otherif와 otherif의 경우 두 개의 정적 분기만 허용합니다.원인이 되는 경우 중첩된 다른 항목 사용
"exception: field inclusion is not allowed inside of $expressions"
여기 내 질문이 있습니다(오류가 발생했습니다).
db.items.aggregate([ { $project :
{
name: 1,
customfield:
{
$cond: { if: { $eq: [ "$field1", "4" ] }, then: 30,
else: {
if:
{ $eq: ["$field1","8"]},
then: 25, else: 10}}
}
}},{ $sort: { customfield: 1 }},{$limit:12}]);
이에 대한 방법이나 해결 방법이 있습니까?반복되는 질문이라면 죄송합니다만, 비슷한 질문을 찾을 수 없었습니다.
MongoDB 3.4 이후의 최신 릴리스에서는 기본적으로 의 대응물인 를 사용합니다.switch
또는case
다른 언어 구현의 키워드:
db.items.aggregate([
{ "$project": {
"name": 1,
"customfield": {
"$switch": {
"branches": [
{ "case": { "$eq": [ "$field1", "4" ] }, "then": 30 },
{ "case": { "$eq": [ "$field1", "8" ] }, "then": 25 }
],
"default": 10
}
}
}},
{ "$sort": { customfield: 1 }},
{ "$limit":12 }
])
이렇게 하면 중첩이 방지됩니다.if..then..else
아래에 표시된 조건을 사용하여 수행할 수 있습니다.하지만 아래는 여전히 명시적인 새로운 연산자 이전에도 이것이 항상 이루어질 수 있다는 것을 예시로 보여줍니다.if..then..else
원래 배열 표기법이 항상 해당 구문을 유지했기 때문에 키워드를 지정할 수 있습니다.
또한 여기서 조건 배열은 일반적으로 에서 필요한 대로 문에 대한 중첩된 데이터 구조를 만드는 것보다 프로그래밍 방식으로 구성하는 것이 훨씬 쉽습니다.
그if..then..else
운영자에 대한 키워드는 작성 당시 최신 버전의 MongoDB에 대한 최근 추가일 뿐입니다(MongoDB 2.6은 키워드의 도입이었습니다).실제 운영자는 MongoDB 2.2)의 집계 프레임워크 릴리스에서 사용할 수 있었습니다.명확성을 위한 의도였지만 이 경우에는 약간의 혼란을 야기한 것으로 보입니다.
if..then.else
연산자는 많은 프로그래밍 언어에서 구현되는 것처럼 실제로 3차 연산자입니다.이는 "인라인" 조건으로서, 조건에 대한 논리의 "블록"을 생성하는 것이 아니라, 첫 번째 조건을 충족하지 않는 모든 것은 다음과 같습니다.else
.
따라서 블럭을 따르는 대신 문을 "둥근"합니다.
db.items.aggregate([
{ "$project": {
"name": 1,
"customfield": {
"$cond": {
"if": { "$eq": [ "$field1", "4" ] },
"then": 30,
"else": {
"$cond": {
"if": { "$eq": ["$field1","8"]},
"then": 25,
"else": 10
}
}
}
}
}},
{ "$sort": { customfield: 1 }},
{ "$limit":12 }
]);
또는 원래 배열 표기법을 사용하더라도 일부는 문을 프로그래밍 방식으로 작성할 때 선호할 수 있습니다.
db.items.aggregate([
{ "$project": {
"name": 1,
"customfield": {
"$cond": [
{ "$eq": [ "$field1", "4" ] },
30,
{ "$cond": [
{ "$eq": ["$field1","8"] },
25,
10
]}
]
}
}},
{ "$sort": { customfield: 1 }},
{ "$limit":12 }
]);
삼차는 그 이상도 이하도 아닌 세 가지 조건을 의미합니다.그래서 다if..then..else
논리는 중첩되어야 합니다.
3에는 MongoDB 3.4라는 .$switch
이 정확한 것을 위하여!
$switch: {
branches: [
{ case: <expression>, then: <expression> },
{ case: <expression>, then: <expression> },
...
],
default: <expression>
}
https://docs.mongodb.com/manual/reference/operator/aggregation/switch/
제가 선호하는 방법은 이렇습니다.
구문
$cond: [ { <condition> }, <true>, <false> ]
예
condition1: {
$cond: [ { $eq: ["one", 'one'] }, true, false ]
},
condition2: {
$cond: [ { $eq: ["one", 'two'] }, true, false ]
},
condition3: {
$cond: [ { $eq: ["three", 'three'] }, {three:'is equal to three'}, {three:'is not equal to three'} ]
}
산출량
{
condition1: true,
condition2: false,
condition3: { three: 'is equal to three' },
}
객체만 사용하는 경우
{
$cond: {
$and: [
{ if: { $eq: ["$$field1", 'A'] }, then: '10', else: 15 },
{ if: { $eq: ["$$field1", 'B'] }, then: '20', else: 15 },
{ if: { $eq: ["$$field1", 'C'] }, then: '10', else: 15 },
]
}
}
어레이를 사용하는 경우 데이터 찾기
{
$map: {
input: "$fields", as: "field1", in: {
$cond: {
$and: [
{ if: { $eq: ["$$field1", 'A'] }, then: '10', else: 15 },
{ if: { $eq: ["$$field1", 'B'] }, then: '20', else: 15 },
{ if: { $eq: ["$$field1", 'C'] }, then: '10', else: 15 },
]
}
}
}
}
언급URL : https://stackoverflow.com/questions/27479347/is-there-an-elseif-thing-in-mongodb-to-cond-while-aggregating
'it-source' 카테고리의 다른 글
문자열에서 클래스 인스턴스 만들기 (0) | 2023.05.06 |
---|---|
특성 오류: 'module' 개체에 'urlopen' 특성이 없습니다. (0) | 2023.05.06 |
postgresql에서 배열 크기를 찾는 방법 (0) | 2023.05.06 |
나머지 화면 공간의 높이를 div로 채웁니다. (0) | 2023.05.06 |
Xcode 5.1 - 컴파일할 아키텍처 없음(ONLY_ACTIVE_ARCH=YES, 활성 arch=x86_64, VALID_ARCS=i386) (0) | 2023.05.06 |